首页 > 代码库 > Decorator

Decorator

#include <iostream>using namespace std;#define DESTROY_POINTER(ptr) if (ptr) { delete ptr; ptr = NULL; } class Product{public:    virtual void Action()=0;};class ConcreteProductA : public Product{public:    ConcreteProductA() {}    ~ConcreteProductA() {}        void Action() { cout<<"ConcreteProductA::Action"<<endl; }};class ConcreteProductB : public Product{public:    ConcreteProductB() {}    ~ConcreteProductB() {}        void Action() { cout<<"ConcreteProductB::Action"<<endl; }};class Decorator : public Product{public:    virtual void Action()=0;};class DecoratorProductA : public Decorator{public:    DecoratorProductA() { m_pProduct = new ConcreteProductA; }    ~DecoratorProductA() { DESTROY_POINTER(m_pProduct); }    void AddModification() { cout<<"DecoratorProductA::AddModification->"; }    void Action()    {        AddModification();        m_pProduct->Action();    }    private:    Product* m_pProduct;};class DecoratorProductB : public Decorator{public:    DecoratorProductB() { m_pProduct = new ConcreteProductB; }    ~DecoratorProductB() { DESTROY_POINTER(m_pProduct); }    void AddModification() { cout<<"DecoratorProductB::AddModification->"; }    void Action()    {        AddModification();        m_pProduct->Action();    }private:    Product* m_pProduct;};int main(int argc, char *argv[]){    Product* pProduct;    pProduct = new ConcreteProductA;    pProduct->Action();    DESTROY_POINTER(pProduct);    pProduct = new ConcreteProductB;    pProduct->Action();    DESTROY_POINTER(pProduct);    Decorator* pDecorator = new DecoratorProductA;    pDecorator->Action();    DESTROY_POINTER(pDecorator);        pDecorator = new DecoratorProductB;    pDecorator->Action();    DESTROY_POINTER(pDecorator);        return 0;}

 

Decorator