c++ - UML 设计模式和 C++ 类的实现

标签 c++ c++11 design-patterns uml

我正在尝试使用 C++ 学习适配器设计模式 UML,并且在 youtube 的一个视频中显示了此内容 - 我的问题是将 UML 图片转换为 C++ 类/代码:
enter image description here
我真正感到困惑的是:

  • Clinet -------> [实线] 与接口(interface) Target 的关联。这通常意味着什么我见过实现接口(interface)的类,例如实现 Target 的适配器类
  • 内容适配器与适配器在这里的含义是什么 - 如果它是容器,那么它是完全还是部分拥有它?

  • 下面是我能想到的代码实现:
    class Target
    {
    public:
     void virtual ServiceA() = 0;
    }; 
    
    class Client : public Target
    {
    public:
    Client(){}
    void ServiceA() override {}
    };
    
    class Adaptee
    {
    public:
    Adaptee(){}
    void ServiceX(){}
    };
    
    class Adapter : public Target
    {
    public:
    Adapter(){}
    void ServiceA() override {adaptee.serviceX();}
    Adaptee adaptee;
    };
    
    int main()
    {
    .....
    }
    
    我们将如何在 main 中编写代码?请解释。

    最佳答案

    The Clinet -------> [solid line] association to interface Target. What does this means generally I have seen classes implementing interface something like Adapter class implementing Target


    不,客户端不实现/继承目标,所以
    class Client : public Target {
       ...
    };
    
    是错的。
    关联可以表明Client有一个属性类型为Target,即使真正的类型是Adapter,接口(interface)Target用来隐藏Adapter。当然C++属性的类型不是Target而是指向任何管理它的方式的指针。
    但是该关联可以仅用于指示客户端查看/使用目标(而不是适配器及其关联的 Adaptee),即使在这种情况下依赖关系更好。可以通过类型为Target * 的参数将Adapter 的实例交给Client 的操作。是 C++ 还是其他管理指向 Target 的指针的方式

    What does the content Adapter is composed with the adaptee means here - if it is containership then does it completely or partially owns it?


    适配器需要一个关联的 Adaptee,多重性为 1,但请注意该关联不是组合,因此如果我很好理解您的意思,它并不完全拥有它。请注意,即使图表中的注释谈到组合,关联甚至也不是聚合。

    How inside main we would code up? Please explain.


    该程序可以是:
    #include <iostream>
    
    class Target {
      public:
        virtual void serviceA() = 0;
    };
    
    class Adaptee {
      public:
        void serviceX() { std::cout << "serviceX" << std::endl; }
    };
    
    class Adapter : public Target {
      public:
        Adapter(Adaptee & a) : adaptee(a) {}
        virtual void serviceA() { adaptee.serviceX(); }
      private:
        Adaptee & adaptee;
    };
    
    class Client {
      public:
        void work(Target & t) { t.serviceA(); }
    };
    
    int main()
    {
      Adaptee adaptee;
      Adapter adapter(adaptee);
      Client client;
      
      client.work(adapter);
    }
    
    编译和执行:
    pi@raspberrypi:/tmp $ g++ -Wall c.cc
    pi@raspberrypi:/tmp $ ./a.out
    serviceX
    pi@raspberrypi:/tmp $ 
    

    关于c++ - UML 设计模式和 C++ 类的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62606403/

    相关文章:

    c# - 如何解决这个通用的存储库模式问题?

    c++ - 使用 SFML 精确事件计时

    c++ - 测试 std::pointer_traits 是否适用于我的类型

    c++ - 在 std::abs 函数上

    c++ - 为什么默认情况下 C++1 1's lambda require "mutable"keyword 用于按值捕获?

    design-patterns - 设计模式: exception/error handling

    c++ - 是否可能导致多进程休眠(核心转储?)?

    c++ - is_assignable<> 的结果不一致

    c++ - 使用 std::mutex 实现信号量

    java - 使类更通用