装饰器模式和代理模式很像。
代理模式是已经知道代理谁了,所以只是对委托类的访问权限进行限制,因此用户只需要访问相应的代理类就可以。装饰器模式并不知道要装饰谁,所以需要传入具体的被装饰对象进行功能的添加
目的:
增加现有类的功能,但是,增加现有类的功能还有一个方法,就是新增加一个子类
添加子类的缺点:功能虽然可以完成,但是代码中有太多的子类添加进来,相同功能的代码大多相同,代码冗余严重
代码实现
#include<iostream>
#include<mutex>
#include<memory>
#include<unordered_map>
#include<list>
using namespace std;
class Car
{
public:
virtual void Show() = 0;
};
class Bmw:public Car
{
public:
void Show()
{
cout << "这是一辆宝马汽车:有基本配置" << " ";
}
};
class Audi :public Car
{
public:
void Show()
{
cout << "这是一辆奥迪汽车:有基本配置" << " ";
}
};
class Benz :public Car
{
public:
void Show()
{
cout << "这是一辆奔驰汽车:有基本配置" << " ";
}
};
//装饰器1:定速巡航
class ConcreateDecorator01 :public Car
{
public:
ConcreateDecorator01(Car*p):pCar(p){}
void Show()
{
pCar->Show();
cout << "定速巡航" << " ";
}
private:
Car* pCar;
};
//装饰器2:自动刹车
class ConcreateDecorator02 :public Car
{
public:
ConcreateDecorator02(Car* p) :pCar(p) {}
void Show()
{
pCar->Show();
cout << "自动刹车" << " ";
}
private:
Car* pCar;
};
//装饰器3:车道偏离
class ConcreateDecorator03 :public Car
{
public:
ConcreateDecorator03(Car* p) :pCar(p) {}
void Show()
{
pCar->Show();
cout << "车道偏离" << " ";
}
private:
Car* pCar;
};
int main()
{
Car* p1 = new ConcreateDecorator01(new Bmw());
p1= new ConcreateDecorator02(p1);
p1 = new ConcreateDecorator03(p1);
p1->Show();
cout << endl;
Car* p2 = new Audi();
p2 = new ConcreateDecorator02(p2);
p2->Show();
cout << endl;
Car* p3 = new Benz();
p3->Show();
cout << endl;
return 0;
}