合成复用原则:继承和组合,优先使用组合。
这样写,每开一种车,就要弄一个新的Person类。
代码如下:
#include <iostream>
using namespace std;class AbstractCar
{
public:virtual void run() = 0;
};class DaZhong :public AbstractCar
{
public:virtual void run(){cout << "大众车启动" << endl;}
};class TuoLaJi :public AbstractCar
{
public:virtual void run(){cout << "拖拉机启动" << endl;}
};class PersonA:public TuoLaJi
{
public:void Doufen(){run();}
};class PersonB :public DaZhong
{
public:void Doufen(){run();}
};
合成复用原则
代码如下:
#include <iostream>
using namespace std;class AbstractCar
{
public:virtual void run() = 0;
};class DaZhong :public AbstractCar
{
public:virtual void run(){cout << "大众车启动" << endl;}
};class TuoLaJi :public AbstractCar
{
public:virtual void run(){cout << "拖拉机启动" << endl;}
};class Person
{
public:void setCar(AbstractCar *car){this->car = car;}void Doufeng(){this->car->run();if (this->car != nullptr){delete this->car;}this->car = nullptr;}AbstractCar *car;
};void test01()
{Person *p = new Person;p->setCar(new DaZhong);p->Doufeng();p->setCar(new TuoLaJi);p->Doufeng();
}int main()
{test01();return 0;
}
测试结果: