设计模式之装饰模式Decorator

来源:互联网 发布:java log4j jar下载 编辑:程序博客网 时间:2024/06/02 03:17

动态地给一个对象扩展功能,而不是通过子类继承。



代码示例:

//The Window interface classclass Window{public://Draws the Windowvirtual void draw() = 0;//Returns a description of the Windowvirtual string getDescription() = 0;};//Implementation of a simple Window without any scrollbarsclass SimpleWindow : public Window{public:virtual void draw() override{//Draw window}virtual string getDescription() override{return "simple window";}};//abstract decorator class - note that it implements windowclass WindowDecorator : public Window{protected:Window* _windowToBeDecorated; //the window being decoratedpublic:WindowDecorator(Window* windowToBeDecorated){_windowToBeDecorated = windowToBeDecorated;}virtual void draw() override{_windowToBeDecorated->draw(); //Delegation}virtual string getDescription() override{return _windowToBeDecorated->getDescription(); //Delegation}};//The first concrete decorator which adds vertical scrollbar functionalityclass VerticalScrollBarDecorator : public WindowDecorator{public:VerticalScrollBarDecorator(Window* windowToBeDecorated): WindowDecorator(windowToBeDecorated){}virtual void draw() override{WindowDecorator::draw();drawVerticalScrollBar();}virtual string getDescription(){return WindowDecorator::getDescription() + ", including vertical scrollbars";}private:void drawVerticalScrollBar(){//Draw the vertical scrollbar}};//The second concrete decorator which adds horizontal scrollbar functionalityclass HorizontalScrollBarDecorator : public  WindowDecorator{public:HorizontalScrollBarDecorator(Window* windowToBeDecorated): WindowDecorator(windowToBeDecorated){}virtual void draw() override{WindowDecorator::draw();drawHorizontalScrollBar();}virtual string getDescription(){return WindowDecorator::getDescription() + ", including horizontal scrollbars";}private:void drawHorizontalScrollBar(){//Draw the horizontal scrollbar}};void main(){//create a decorated window with horizontal and vertical scrollbars.Window* decoratedWindow = new HorizontalScrollBarDecorator(new VerticalScrollBarDecorator(new SimpleWindow));//Print the window's descriptiondecoratedWindow->getDescription();}



原创粉丝点击