漫谈设计模式之装饰模式(Decorator)

来源:互联网 发布:算法类书籍推荐 编辑:程序博客网 时间:2024/06/10 17:26

什么是装饰模式(Decorator)?装饰模式又叫装饰者模式属于结构型设计模式之一。在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰(对象)来包裹真实的对象。


装饰模式的设计原则:

1.多用组合,少用继承。利用继承设计子类的行为,是在编译时静态决定的,而且所有的子类都会继承到相同的行为。然而,如果能够利用组合的做法扩展对象的行为,就可以在运行时动态的进行扩展。

2.类应设计的对扩展开放,对修改关闭。


装饰模式UML结构图:

Component是定义一个对象接口,可以给这些对象动态地添加职责。ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责。Decorator,装饰着抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在的。至于ConcreteDecorator就是具体的装饰对象,起到给Component添加职责的功能。


示例代码:

#include <iostream>using namespace std;/** * @brief The Person class */class Person{public:    Person(string strName) : m_strName(strName) {    }    Person() {}    virtual ~Person() {}    virtual void show() {        cout<<"Decorate is "<<m_strName<<endl;        cout<<"-----------------------\n";    }private:    string m_strName;};/** * @brief The Finery class * 装饰类 */class Finery : public Person{public:    void decorate(Person* component) {        m_component = component;    }    virtual void show() {        m_component->show();    }protected:    Person* m_component;};/** * @brief The TShirts class */class TShirts : public Finery{public:    virtual ~TShirts() {}    virtual void show() {        cout<<"TShirt~\n";        m_component->show();    }};class Trouser : public Finery{public:    virtual ~Trouser() {}    virtual void show() {        cout<<"Trouser~\n";        m_component->show();    }};//clientint main(){    Person* p = new Person("Henry");    TShirts* tshirts = new TShirts();    Trouser* trouser = new Trouser();    tshirts->decorate(p);    tshirts->show();    trouser->decorate(p);    trouser->show();    trouser->decorate(tshirts);    trouser->show();    delete p;    delete tshirts;    delete trouser;    return 0;}


运行结果:

0 0
原创粉丝点击