装饰者模式
作为一个程序员在做程序开发得过程中最烦得莫过于需求更改后对原来代码得更改。这其中带来得问题有可能远远超过需要更改得问题个数。所以如果做到“不更改,只扩展”将会带来直观的改变。而装饰者模式就是解决这个问题的比较实用得一种模式。
装饰者模式:在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。动态地将责任附加到对象上,想要扩展功能,装饰者提供有利于继承的另一种选择。
类图不太好容易理解,下面给出一个小的简单得列子:
超类Component
public abstract class Beverage
{
protected string description = "Unknown Beverage";
public virtual string getDescription() { return description; }
public abstract double cost();
}
需要被装饰的类concreteComponent
public class Espresso:Beverage
{
public Espresso()
{
description = "Espresso";
}
public override double cost() { return 1.99; }
}
装饰者调料父类Decorator
public abstract class CondimentDecorator:Beverage
{
protected Beverage beverage;
public override string getDescription()
{
return beverage.getDescription() +","+ description;
}
}
其中得一个调料concreteComponentA
public class Mocha : CondimentDecorator
{
public Mocha(Beverage beverageTemp)
{
beverage = beverageTemp;
description = "Mocha";
}
public override double cost()
{
return beverage.cost() + 0.2;
}
}
最后的使用
Beverage espresso = new Espresso();
MessageBox.Show(espresso.getDescription()+" 的咖啡价钱为:"+espresso.cost().ToString());
Beverage espressoTemp = new Espresso();
espressoTemp = new Mocha(espressoTemp);
espressoTemp = new Mocha(espressoTemp);
MessageBox.Show(espressoTemp.getDescription() + " 的咖啡价钱为:" + espressoTemp.cost().ToString());
在其中你可以添加很多中调味料,以及咖啡。
个人感悟:
在使用装饰者模式得时候一定要抽出里面得变化然后进行抽象。至于里面得变化需要具体问题具体分析。抽取变化得时候没有啥好办法就是要多多练习,积累经验。