如果你有一杯咖啡,你可以往里面加牛奶,同时也可以加糖。各种咖啡价格都不同,如此可能得到下面的类层次。
- class Coffee { public: virtual double cost() { return 1; } };
- class CoffeeWithMilk : public Coffee { public: virtual double cost() { return 2; } };
- class CoffeeWithSugar : public Coffee { public: virtual double cost() { return 1.5; } };
- class CoffeeWithSugarAndMilk : public Coffee { public: virtual double cost() { return 2.5; } };
如果我同时可以加入豆浆或者蜂蜜,那么类的数量会瞬间膨胀。这时装饰者模式可以派上用场。
- class CoffeeDecorator : public Coffee
- {
- protected:
- CoffeeDecorator(Coffee* pCoffee) : mpCoffee(pCoffee) {}
- Coffee* mpCoffee;
- };
- class MilkDecorator : public CoffeeDecorator
- {
- public:
- MilkDecorator(Coffee* coffee) : CoffeeDecorator(pCoffee) {}
- virtual double cost() { return mpCoffee->cost() + 1; }
- };
- class SugarDecorator : public CoffeeDecorator
- {
- public:
- SugarDecorator(Coffee* coffee) : CoffeeDecorator(pCoffee) {}
- virtual double cost() { return mpCoffee->cost() + 0.5; }
- };
如此一来就可以随意搭配这杯咖啡,甚至可以同时加两杯牛奶:
- int main()
- {
- Coffee* pCoffee = new MilkDecorator(new SugarDecorator(new Coffee));
- double d = pCoffee->cost();
- return 0;
- }
设计原则:类应该对扩展开放,对修改关闭。 (开放-关闭原则)
阅读(932) | 评论(0) | 转发(0) |