UML 设计模式和 C++ 实现 类

UML Design Pattern and implementation into C++ classes

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

我真正感到困惑的是:

  1. Clinet ------> [实线] 关联到接口 Target。这通常意味着什么?我看到 classes 实现接口,类似于 Adapter class 实现 Target

  2. 什么是content Adapter is composed with the adaptee means here - 如果是containership那么它是完全拥有还是部分拥有它?

下面是我能想到的代码实现:

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

不,Client 没有 implement/inherit Target,所以

class Client : public Target {
   ...
};

错了。

关联可以指示 Client 具有类型为 Target 的属性,即使实际类型是 Adapter,接口Target用于隐藏Adapter。当然 C++ 属性的类型不是 Target 而是指向任何管理方式的指针。

但是关联可以用来指示 Client see/use Target (而不是 Adapter 及其关联的 Adaptee) 即使在那种情况下依赖性更好。 Adapter 的实例可以通过类型为 Target * 的参数提供给 Client 的操作是 C++ 或管理指针的其他方式目标

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

Adapter 需要关联的 Adaptee,重数为 1,但请注意关联不是组合,因此它不会 完全拥有它 如果我很明白你的意思。请注意,该关联甚至不是聚合,即使图中的注释也提到 composed.

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 $