我正在尝试使用 C++ 学习适配器设计模式 UML,并且在 youtube 的一个视频中显示了此内容 - 我的问题是将 UML 图片转换为 C++ 类/代码:
我真正感到困惑的是:
下面是我能想到的代码实现:
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/