Decorator(装饰)

9. Decorator(装饰)

9.1定义

  动态地给一个对象添加一些额外的职责。就增加功能来说,装饰模式比生成子类更为灵活。

9.2.优点

  ■ 装饰类和被装饰类可以独立发展,而不会相互耦合。即 Component 类无须知道Decorator类,Decorator类是从外部来扩展Component类的功能,而Decorator也不用知道具体的构件。

  ■ 装饰模式是继承关系的一个替代方案。装饰类Decorator,不管装饰多少层,返回的对象还是Component。、

  ■ 装饰模式可以动态地扩展一个实现类的功能。

9.3 缺点

  多层的装饰是比较复杂的。

9.4 使用场景

  ■ 需要扩展一个类的功能,或给一个类增加附加功能。

  ■ 需要动态地给一个对象增加功能,这些功能可以再动态地撤销。

  ■ 需要为一批类进行改装或加装功能。装饰模式是对继承的有力补充。单纯使用继承时,在一些情况下就会增加很多子类,而且灵活性差,维护也不容易。装饰模式可以替代继承,解决类膨胀的问题

 1 #include<iostream>
 2 using namespace std;
 3 //抽象装饰对象
 4 class Car{
 5 public:
 6     virtual void show() = 0;
 7 };
 8 
 9 //具体装饰对象
10 class Benz:public Car{
11     void show(){
12         cout<<"奔驰车默认为黑色"<<endl;
13     }
14 };
15 
16 //装饰角色:该角色持有一个构件对象的实例,并定义一个与抽象构件接口一致的接口。
17 class CarDecorator:public Car{
18 public:
19     CarDecorator(Car* car){
20         this->car = car;
21     }
22     void show(){
23         this->car->show();
24     }
25 private:
26     Car* car;
27 };
28 //具体装饰角色:该角色负责对构件对象进行装饰。
29 class ConcreteCarDecorator:public CarDecorator{
30 public:
31         ConcreteCarDecorator(Car* car):CarDecorator(car){}
32         void show(){
33                 CarDecorator::show();
34                 print();
35                 setGps();
36         }
37 private:
38     void print(){
39         cout<<"绘制字样"<<endl;
40     }
41     void setGps(){
42         cout<<"安装GPS"<<endl;
43     }
44 };
45 int main(){
46     Car* car = new Benz();
47     CarDecorator* cd = new ConcreteCarDecorator(car);
48     cd->show();
49     delete cd;
50     cd = NULL;
51     delete car;
52     car = NULL;
53 }

 

posted @ 2020-11-06 10:01  昨日明眸  阅读(137)  评论(0)    收藏  举报