设计模式之装饰者模式Decorator Pattern

        近来在读《Head first设计模式》这本书,感觉很不错只是书中的代码是用Java写的。因为我熟悉的是C++,于是自己写了C++的例子程序。首先说说我的感受吧,学C++的话,先看《C++ Primer》搞明白了C++的各种语法,对封装、继承、多态有初步的认识。然后学点设计模式,设计模式是针对具体事例的解决方案,是前人编程的经验,很值得借鉴!

        说个具体事例吧,在买电脑的时候我们通常会填一个表单。表单中有电脑、鼠标、键盘、耳机、话筒、清洁套装等等。卖家会根据我们的选择计算价格。如果要针对这个事例写个程序该怎么处理呢?当然我们最直接的想法就是针对每一个选项设置一个布尔型变量,值为真的时候代表你选择了,值为假的时候代表你没选。但是这样有很多缺陷比方说,我以后要添加新的设备供客户选择怎么办?客户选择了两个鼠标怎么办。。。。出现这样的需求变化时我们只能修改以前写的代码。这样的程序不符合“对扩展开放,对修改关闭”的原则。

       装饰模式是在不必改变原类文件和使用继承的情况下,动态的扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。

       下面是我用c++写的代码:

#include <iostream>
#include <string>
using namespace std;

class Component
{
public:
	virtual float cost(){return price;}
	virtual string GetDescription(){return description;}
private:
	float price;
	string description;
};
class Computer : public Component
{
public:
	float cost(){return 5000.0;}
	string GetDescription(){return "Computer";}
};
class Mouse : public Component
{
public:
	Mouse(Component *com){component=com;}
	float cost(){return 50+component->cost();}
	string GetDescription(){return "Mouse "+component->GetDescription();}
private:
	Component *component;
};
class Battery : public Component
{
public:
	Battery(Component *com){component=com;}
	float cost(){return 200.0+component->cost();}
	string GetDescription(){return "Battery "+component->GetDescription();}
private:
	Component *component;
};
void main()
{
	int choose;
	int flg=0;
	Component *com;
	cout<<"Please input your choose:"<<endl;
	cout<<"1: Computer  2: Mouse  3: Batery  4:Quit"<<endl;
	while (1)
	{
		cin>>choose;
		switch (choose)
		{
		case 1:com=new Computer();
			break;
		case 2:com=new Mouse(com); 
			break;
		case 3:com=new Battery(com); 
			break;
		case 4: flg=1; break;
		default: break;
		}
		if (1==flg)
		{
			flg=0;
			break;
		}
	}
	cout<<com->GetDescription()<<endl;
	cout<<com->cost()<<endl;
}


原文地址:https://www.cnblogs.com/bbsno1/p/3266480.html