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

来源:互联网 发布:手机账本软件哪个好 编辑:程序博客网 时间:2024/05/26 14:12
/*
* 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();}