Understand decorator design pattern

  The Decorator Pattern is used for adding additional functionality to a particular object as opposed to a class of objects. It is easy to add functionality to an entire class of objects by subclassing an object, but it is impossible to extend a single object this way. With the Decorator Pattern, you can add functionality to a single object and leave others like it unmodified.
   A Decorator, also known as a Wrapper, is an object that has an interface identical to an object that it contains. Any calls that the decorator gets, it relays to the object that it contains, and adds its own functionality along the way, either before or after the call. This gives you a lot of flexibility, since you can change what the decorator does at runtime, as opposed to having the change be static and determined at compile time by subclassing. Since a Decorator complies with the interface that the object that it contains, the Decorator is indistinguishable from the object that it contains.  That is, a Decorator is a concrete instance of the abstract class, and thus is indistinguishable from any other concrete instance, including other decorators.   This can be used to great advantage, as you can recursively nest decorators without any other objects being able to tell the difference, allowing a near infinite amount of customization.



An example:

#include  < iostream >
class  IntCompute {
public:
    virtual 
int Compute(int,int=0;
}
;
class  IntComputeAdd: public  IntCompute {
public:
int Compute(int a,int b){
    
return a+b;
}

}
;
class  DecorateMinusAdd: public  IntCompute {
private:
    IntComputeAdd intadd;
public:
    
int Compute(int a,int b)
    
{
      
return -(intadd.Compute(a,b));

    }

}
;
class  DecorateSumSquare: public  IntCompute {
private:
    IntComputeAdd intadd;
public:
    
int Compute(int a,int b)
    
{
        
int result=intadd.Compute(a,b);
        
return result*result;

    }

}
;
int  main()
{
 
DecorateMinusAdd minadd;
DecorateSumSquare sumsquare;
std::cout
<<minadd.Compute(10,20)<<std::endl;
std::cout
<<sumsquare.Compute(10,20)<<std::endl;
 
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值