C++设计模式Decorator简单实现

/*
* Decorator可以为对象而不是整个类扩展功能,并且原部件不需要知道扩展的存在
* 本模式非常适合与现有架构的修改而不是重构,并且适合于基础部件(abstract component)体积较小的场合
* 如果基础部件本身很大,更适合用Strategy模式,为部件注册策略类并执行各策略
*/
#include<stdio.h>
class VisualComponent {
    public:
        VisualComponent(){}

        virtual void Draw() = 0;
        virtual void Resize() = 0;
};
class TextView : public VisualComponent{
    public:
        TextView(){}
        
        virtual void Draw();
        virtual void Resize();
};
void TextView::Draw(){
    printf("Drawing TextView\n");
}
void TextView::Resize(){

}
class Decorator : public VisualComponent {
    public:
        Decorator(VisualComponent* component):_component(component){}

        virtual void Draw();
        virtual void Resize();
    private:
        VisualComponent* _component;
};

void Decorator::Draw() {
    _component->Draw();
}
void Decorator::Resize() {
    _component->Resize();
}

class BorderDecorator : public Decorator {
    public:
        BorderDecorator(VisualComponent* component, int borderWidth):Decorator(component),
            _width(borderWidth){}
        
        virtual void Draw();
    private:
        void DrawBorder(int);
    private:
        int _width;
};

void BorderDecorator::DrawBorder(int width){
    printf("Border:%d\n", width);
}
void BorderDecorator::Draw(){
    Decorator::Draw();
    DrawBorder(_width);
}
int main(){
    TextView *textptr = new TextView;
    textptr->Draw();
    BorderDecorator *bordertextptr = new BorderDecorator(textptr, 10);
    bordertextptr->Draw();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值