Design Pattern --- Decorator

class Component
{
public:
    virtual void Operation() = 0;
};
class ConcreteComponent : public Component
{
public:
    // Interface.
    virtual void Operation() override { cout <<"ConcreteComponent::Operation()." <<endl; }
};

class Decorator : public Component
{
protected:
    // data.
    Component *m_component;

public:
    Decorator(Component *component) : m_component(component) {}
};
class ConcreteDecorator : public Decorator
{
public:
    ConcreteDecorator(Component *component) : Decorator(component) {}

public:
    // Interface.
    virtual void Operation() override 
    {
        m_component->Operation();
        AddedBehavior();
    }

private:
    // logic.
    void AddedBehavior() { cout <<"ConcreteDecorator::AddedBehavior()." <<endl; }
};



int main(int argc, char *argv[])
{
    ConcreteDecorator cd(new ConcreteComponent);

    cd.Operation();

    // TODO: release memory.
    
    return 0;
}

Decorator 和 Composite 核心思想相同, 都是通过继承, 来统一对待 “单个对象” 和 “多个对象集合”。
Composite 使对多个对象实例像单个对象实例一样操作, Decorator 使对多个操作(可能来自不同的对象实例)就像对一个操作一样。
“为文本控件增加边框” 就是典型的应用。绘制文本的对象 A 和嵌套在 A 外层的 DecoratorA (负责绘制边框)。

 

posted @ 2013-01-24 17:53  walfud  阅读(137)  评论(0编辑  收藏  举报