设为首页 加入收藏

TOP

设计模式之装饰者模式Decorator Pattern
2014-11-23 19:38:01 来源: 作者: 【 】 浏览:12
Tags:设计模式 装饰 模式 Decorator Pattern

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

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

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

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

#include 
#include 
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:"<>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<GetDescription()<cost()< 
 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇POJ 1159 Palindrome (动态规划) 下一篇nyist 510昂贵的聘礼

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·C语言中,“指针”用 (2025-12-26 15:20:18)
·在c语言的指针运算中 (2025-12-26 15:20:15)
·C语言-函数指针与函 (2025-12-26 15:20:12)
·求navicat for mysql (2025-12-26 13:21:33)
·有哪位大哥推荐一下m (2025-12-26 13:21:30)