设计模式之装饰模式

装饰模式

1.功能

将主功能和附加功能分开

 

2.好处

(1)使主功能和附加功能可以独立扩展

(2)降低主功能和附加功能之间的耦合度

 

3.基本类图

 

内存中:

4.装饰模式的一个具体事例

(1)类图

(2)代码实现如下

#include <iostream>
using namespace std;

class Base{
	private:
		Base * next;
	public:
		Base(Base*t){
			next=t;
		}
		
		virtual void fun(){
			if(next){
				next->fun();
			}
		}
		
		virtual ~Base(){
			delete next;
			cout<<"Base的析构函数"<<endl; 
		} 
};

class productA: public Base{
	public:
		productA(Base *t):Base(t){
		}
		~productA(){
			cout<<"productA的析构函数"<<endl; 
		}
};

class productB: public Base{
	public:
		productB(Base *t):Base(t){
		}
		~productB(){
			cout<<"productB的析构函数"<<endl; 
		}
};

class Decorator:public Base{
	public:
		Decorator(Base*t):Base(t){
		}
		virtual void fun()=0;//保证接口继承统一性,也可以不写
		virtual ~Decorator(){
			cout<<"Decorator的析构函数"<<endl; 
		} 
};

class DecoratorA:public Decorator{
	public:
		DecoratorA(Base*t):Decorator(t){
		}
		void fun(){
			cout<<"DecoratorA的fun函数..."<<endl;
			Base::fun(); 
		}
	~DecoratorA(){
			cout<<"DecoratorA的析构函数..."<<endl;
		}
};

class DecoratorB:public Decorator{
	public:
		DecoratorB(Base*t):Decorator(t){
		}
		void fun(){
			cout<<"DecoratorB的fun函数..."<<endl;
			Base::fun(); 
		}
		~DecoratorB(){
			cout<<"DecoratorB的析构函数..."<<endl;
		}
	
};

class DecoratorC:public Decorator{
	public:
		DecoratorC(Base*t):Decorator(t){
		}
		void fun(){
			cout<<"DecoratorC的fun函数..."<<endl;
			Base::fun(); 
		}
		
		~DecoratorC(){
			cout<<"DecoratorC的析构函数..."<<endl;
		}
	
};

int main(void){
	Base*head=NULL;
	head=new DecoratorB(head);
	head=new DecoratorA(head);
	head=new productA(head);
	head->fun();
	delete head;
}

执行结果如下

DecoratorA的fun函数...
DecoratorB的fun函数...
productA的析构函数
DecoratorA的析构函数...
Decorator的析构函数
DecoratorB的析构函数...
Decorator的析构函数
Base的析构函数
Base的析构函数
Base的析构函数

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值