您的位置:首页 > 其它

设计模式:装饰模式

2016-02-01 13:45 363 查看
装饰模式:

1 动态地给一个对象添加一些额外的功能。

2 给对象添加功能,可以直接修改类,添加相应的功能;也可以派生对应的子类来扩展;又可以使用组合,我们应该尽量使用对象组合。

3 定义一个简单的类,并且用装饰类给它逐渐地添加功能,从简单的部件组合出复杂的功能。

例如给一个电脑装屏幕保护、键盘保护:

#include<iostream>
using namespace std;
//抽象电脑类
class Computer{
public:
virtual ~Computer(){}
virtual void show(){};
};
//具体电脑类
class LenovoComputer:public Computer{
public:
void show(){
cout<<"LenovoComputer"<<endl;
}
};
//装饰电脑类
class DecoratorComputer:public Computer{
public:
DecoratorComputer(Computer* computer){
mComputer=computer;
}
virtual void show(){
mComputer->show();
}
private:
Computer* mComputer;
};
//具体装饰电脑类
class ScreenProtectorComputer:public DecoratorComputer{
public:
ScreenProtectorComputer(Computer* computer):DecoratorComputer(computer){}
void show(){
DecoratorComputer::show();
add();
}
void add(){
cout<<"Add ScreenProtector"<<endl;
}
};
//具体装饰电脑类
class KeyboardProtectorComputer:public DecoratorComputer{
public:
KeyboardProtectorComputer(Computer* computer):DecoratorComputer(computer){}
void show(){
DecoratorComputer::show();
add();
}
void add(){
cout<<"Add KeyboardProtector"<<endl;
}
};
int main(){
Computer* LenovoY470=new LenovoComputer;
//加屏幕保护膜
DecoratorComputer* aScreenProtectorComputer=new ScreenProtectorComputer(LenovoY470);
aScreenProtectorComputer->show();
cout<<"-------------------------"<<endl;
//再加键盘保护膜
DecoratorComputer* aKeyboardProtectorComputer=new KeyboardProtectorComputer(aScreenProtectorComputer);
aKeyboardProtectorComputer->show();

delete LenovoY470;
LenovoY470=NULL;
delete aScreenProtectorComputer;
aScreenProtectorComputer=NULL;
delete aKeyboardProtectorComputer;
aKeyboardProtectorComputer=NULL;
return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: