一 合成/聚合使用原则
二 概念
三 UML图
四 C++代码实现
#include "pch.h"
#include <iostream>
using namespace std;
//手机软件 Imolementor
class HandsetSoft
{
public:
virtual void Run() = 0;
};
//手机游戏 ConcreteImplementorA
class HandsetGame : public HandsetSoft
{
public:
void Run() override
{
cout << "运行手机游戏" << endl;
}
private:
};
//通讯录 ConcreteImplementorB
class HandsetAddressList : public HandsetSoft
{
public:
void Run() override
{
cout << "运行手机通信录" << endl;
}
};
//手机品牌 Abstraction
class HandsetBrand
{
public:
void SetHandsetSoft(HandsetSoft* soft)
{
this->soft = soft;
}
virtual void Run() = 0;
protected:
HandsetSoft* soft;
};
//品牌N品牌M具体类 RefinedAbstraction
class HandsetBrandN : public HandsetBrand
{
public:
void Run() override
{
this->soft->Run();
}
};
class HandsetBrandM : public HandsetBrand
{
public:
void Run() override
{
this->soft->Run();
}
};
//客户端调用代码
int main()
{
HandsetBrand* ab;
ab = new HandsetBrandN();
ab->SetHandsetSoft(new HandsetGame());
ab->Run();
ab->SetHandsetSoft(new HandsetAddressList());
ab->Run();
ab = new HandsetBrandM();
ab->SetHandsetSoft(new HandsetGame());
ab->Run();
ab->SetHandsetSoft(new HandsetAddressList());
ab->Run();
system("pause");
return 0;
}
原文:https://www.cnblogs.com/Manual-Linux/p/11140864.html