设计模式(4)---装饰模式

  装饰模式:动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。

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

  

#include "stdafx.h"
#include <memory>
#include <string>
#include <iostream>
using namespace std;

class Person
{
public:
    Person(string name = ""): name_(name)
    {}
    virtual void Show()
    {
        cout << "My name is :" << name_ << endl;
    }
protected:
    string name_;
};

class Finery : public Person
{
public:
    void Decorator(shared_ptr<Person> person)
    {
        person_ = person;
    }
    virtual void Show()
    {
        if (nullptr != person_)
        {
            person_->Show();
        }
    }
protected:
    shared_ptr<Person> person_;
};

class TShirt :public Finery
{
public:
    virtual void Show()
    {
        cout << "This is TShirt." << endl;
        person_->Show();
    }
};

class Sneaker : public Finery
{
public:
    virtual void Show()
    {
        cout << "This is Sneaker." << endl;
        person_->Show();
    }
};

int main()
{
    auto person  = make_shared<Person>("cauchy");
    auto tshirt  = make_shared<TShirt>();
    auto sneaker = make_shared<Sneaker>();
    tshirt->Decorator(person);
    tshirt->Show();
    sneaker->Decorator(tshirt);
    sneaker->Show();

    return 0;
}

  上例中的Person就相当于ConcreteComponent,而Finery就相当于Decorator,而Tshirt和Sneaker就是ConcreteComponent。

  总结:装饰模式是为已有功能动态地添加更多功能的一种方式,当系统需要新功能的时候,是向旧的类中添加新的代码。这些新加的代码通常装饰了原有类的核心职责或主要行为,他们在主类中加入了新的字段,新的方法和新的逻辑,从而增加了主类的复杂度。而装饰模式却提供了一个非常好的解决方案,它把每个要装饰的功能都放在单独的类中,并让这个类包装他索要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择地、按顺序地使用装饰功能包装对象。并且,装饰模式能有效地把类的核心职责和装饰功能区分开来,而且可以去除相关类中重复的逻辑。

 

posted @ 2016-03-28 22:54  制造天堂  阅读(169)  评论(0)    收藏  举报