Decorate 模式

作用:

装饰器模式有助于将其他行为或责任动态附加到对象,装饰器为扩展功能提供了子类化的灵活替代方案。这也被称为包装。如果您的应用程序进行某种过滤,那么装饰器可能是考虑这项工作的良好模式。

#include 
#include 
using namespace std;

class Car
{
protected:
    string _str;
public:
    Car()
    {
    _str = "Unknown Car";
    }
    virtual string getDescription()
    {
        return _str;
    }
    virtual double getCost() = 0;
    virtual ~Car()
    {
        cout<<"~Car \n";
    }
};

class OptionsDecorator:public Car
{
public:
    virtual string getDescription() = 0;
    virtual ~OptionsDecorator()
    {
        cout<<"~OptionsDecorator"<getDescription() + ",Navigation";
    }

    double getCost()
    {
        return _b->getCost() + 300;
    }

    ~Navigation()
    {
        cout<<"~Navigation"<getDescription() + ", PremiumSoundSystem";
                }

                double getCost()
                {
                        return 0.30 + _b->getCost();
                }
                ~PremiumSoundSystem()
                {
                        cout << "~PremiumSoundSystem()\n";
                        delete _b;
                }
};

class ManualTransmission: public OptionsDecorator
{
                Car *_b;
        public:
                ManualTransmission(Car *b)
                {
                        _b = b;
                }
                string getDescription()
                {
		        return _b->getDescription()+ ", ManualTransmission";
                }

                double getCost()
                {
                        return 0.30 + _b->getCost();
                }
                ~ManualTransmission()
                {
                        cout << "~ManualTransmission()\n";
                        delete _b;
                }
};

int main()
{
    //Create our Car that we want to buy
        Car *b = new CarModel1();

        cout << "Base model of " << b->getDescription() << " costs $" << b->getCost() << "\n";

        //Who wants base model let's add some more features

        b = new Navigation(b);
        cout << b->getDescription() << " will cost you $" << b->getCost() << "\n";
        b = new PremiumSoundSystem(b);
        b = new ManualTransmission(b);
        cout << b->getDescription() << " will cost you $" << b->getCost() << "\n";

        // WARNING! Here we leak the CarModel1, Navigation and PremiumSoundSystem objects!
        // Either we delete them explicitly or rewrite the Decorators to take
        // ownership and delete their Cars when destroyed.
        delete b;

        return 0;
}

你可能感兴趣的:(Decorate 模式)