介绍
增加现有类的功能,通过实现子类的方式,重写接口可以完成功能扩展,但是代码中有太多子类,用装饰器可大幅度减少子类数量
实现代码
实例场景:使用装饰器模式动态为不同汽车添加不同的功能,如定速巡航等。
注意装饰器是继承自汽车抽象基类
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 ConcreteDecorator01 : public Car
{
public:
ConcreteDecorator01(Car *p) :pCar(p) {}
void show()
{
pCar->show();
cout << ",定速巡航";
}
private:
Car* pCar;
};
class ConcreteDecorator02 : public Car
{
public:
ConcreteDecorator02(Car* p) :pCar(p) {}
void show()
{
pCar->show();
cout << ",自动刹车";
}
private:
Car* pCar;
};
class ConcreteDecorator03 : public Car
{
public:
ConcreteDecorator03(Car* p) :pCar(p) {}
void show()
{
pCar->show();
cout << ",车道偏离";
}
private:
Car* pCar;
};
int main()
{
Car* p1 = new ConcreteDecorator01(new Bmw());
p1->show();
cout << endl;
Car* p2 = new ConcreteDecorator02(new Audi());
p2 = new ConcreteDecorator01(p2); // 父类指针 = 子类对象地址
p2 = new ConcreteDecorator03(p2);
p2->show();
cout << endl;
Car* p3 = new ConcreteDecorator03(new Benz());
p3->show();
cout << endl;
return 0;
}