c++ 限制核心 class 可见性并提供干净的界面

c++ Limiting core class visibility and providing clean interface

我有一个具有核心逻辑的 Engine class,但是这个 class 有可能被具有类似功能的第三方引擎取代,所以我想要最小对应用程序其余部分的影响。

我有另一个名为 Adapter 的 class,它允许与 Engine class 进行简单的接口,并且还在 [=12 之上提供了一些增值功能=] class.

然后我有另一个名为 OrderProcessor 的 class,我想将其公开给具有更简单界面的应用程序的其余部分。

我希望 EngineAdapter 对应用程序的其余部分隐藏,并且 OrderProcesseor 作为应用程序其余部分的唯一接口。

我该如何设计这个以及在什么地方使用哪个访问修饰符?有设计模式吗?

这是我的,但我觉得不对。

//This is the core functionality. Might have to replace this class with a third //party implementation
//Want to hide it as much as possible
class Engine
{
private:
    char* ip;
    char* port;

protected:
    Engine();

    bool Connect();
    bool DisConnect();
    bool SendOrder(Message msg);
    bool CancelOrder (CancelMessage cxl);
    Message ReceiveOrder();
};


//This is an interface to the engine and provides value added functions
//Don't want this known to anyone except the OrderPRocessor
class Adapter : public Engine
{
private:
    int TotalAmount;
    double DollarAmount;

protected:
    bool Start(char*ip, char* port); //this will call Engine's connect() and do other things
    bool Stop (); //this will call Engine's Disconnect
    int TotalInventory();
    double TotalSales();
    double TotalCommission();    
};


//This class is the main interface to the rest of the application for order 
//processing related functionality.
class OrderProcessor 
{
public:
    OrderProcessor();
    ~OrderProcessor();
    Stats SendStats();
    ManageInventory();

private:
    Adapter adapter;
};

EngineAdapter 设为私有 嵌套 类 of OrderProcessor:

class OrderProcessor 
{
public:
    OrderProcessor();
    ~OrderProcessor();

    Stats SendStats();
    ManageInventory();

private:
    class Engine
    {
        // ...
    };

    class Adapter : public Engine
    {
        // ...
    };

    Adapter adapter;
};

如果您想要更精细的访问限制,请'key tags':

class OrderProcessor
{
public:
    class OpenSesame
    {
        friend ClassThatCanAccessTreasure;
    private:
        OpenSezame() {}; // = default is not sufficient
    };

    int AccessTreasure(int arg1, int arg2, OpenSesame key = {});
};

请注意,在上面的方案中,您不需要传递 key,因为它是默认的。由于默认值是在调用者上下文中实例化的,因此只有 OpenSesame 的朋友可以调用 AccessTreasure。只要您没有 varargs/parameter 包,此默认方案就有效;如果你这样做,你需要在那些之前传递它并手动传递它。