C++设计模式5:装饰器模式

        装饰器模式主要用于增加现有类的功能,一般,我们为了增加现有类的功能,通过实现子类的方式重写接口,是可以完成功能扩展的,但是代码中有太多的子类添加进来了,装饰器模式可以让我们以较小的代价,实现类功能的增加。 

#include
using namespace std;
class Car
{
public:
	Car() {}
	~Car() {}
	virtual void show() = 0;
};
class Audi:public Car
{
public:
	Audi() {}
	~Audi() {}
	void show()
	{
		cout << "this is Audi";
	}
};
class BaoMa:public Car
{
public:
	BaoMa() {}
	~BaoMa() {}
	void show()
	{
		cout << "this is BaoMa";
	}
};
class Decorator:public Car
{
public:
	Decorator(Car *car) :mycar(car){}
	~Decorator() {}
	virtual void show() = 0;
private:
Car* mycar;
};
class Decorator1 :public Car
{
public:
	Decorator1(Car* car) :mycar(car) {}
	~Decorator1() {}
	void show()
	{
		mycar->show();
		cout << ",空调功能" ;
	}
private:
	Car* mycar;
};
class Decorator2 :public Car
{
public:
	Decorator2(Car* car) :mycar(car) {}
	~Decorator2() {}
	void show()
	{
		mycar->show();
		cout << ",音乐功能";
	}
private:
	Car* mycar;
};
class Decorator3 :public Car
{
public:
	Decorator3(Car* car) :mycar(car) {}
	~Decorator3() {}
	 void show()
	{
		 mycar->show();
		 cout << ",自动驾驶功能";
	}
private:
	Car* mycar;
};
int main()
{
	Car*audidecorator1(new Decorator1(new Audi()));
	audidecorator1=new Decorator2(audidecorator1);
	audidecorator1->show();
	cout << endl;
	Car*baomadecorator2(new Decorator1(new BaoMa()));
	baomadecorator2->show();
	delete audidecorator1;
	delete baomadecorator2;
	return 0;
}

C++设计模式5:装饰器模式_第1张图片

你可能感兴趣的:(设计模式,c++,设计模式,装饰器模式,c语言,开发语言,结构型模式)