开放-关闭原则
类应该对扩展开放,对修改关闭:当类中需要加入新功能时,可以考虑扩展新的类,而不是修改原有的类。
认识装饰者模式
1、拿一个咖啡为对象
2、以摩卡对象装饰它
3、以牛奶对象装饰它
4、调用cost方法,并依赖委托将调料价格加上
装饰者和被装饰对象有相同额超类型
你可以用一个或多个装饰者包装一个对象
装饰者可以在所委托被装饰者的行为之前或者之后,加上自己的行为,以达到特定的目的
对象可以在任何时候被装饰,所以可以在运行时动态地、不限量地用你喜欢的装饰者来装饰对象
装饰者模式动态的将责任或者特性附加到对象上。若要扩展功能,装饰者提供比继承更有弹性的替代方案
public abstract class Beverage {
String description = "Unknow Beverage";
public String getDescription() {
return description;
}
public abstract double cost();
}
public abstract class CondimentDecorator extends Beverage{
public abstract String getDescription();
}
public class Espresso extends Beverage {
public Espresso(){
description = "Espresso";
}
@Override
public double cost() {
return 1.99;
}
}
public class HouseBlend extends Beverage {
public HouseBlend(){
description = "House Blend Coffee";
}
@Override
public double cost() {
return 0.89;
}
}
public class Mocha extends CondimentDecorator {
Beverage beverage;
public Mocha(Beverage beverage){
this.beverage = beverage;
}
public String getDescription(){
return beverage.getDescription()+",Mocha";
}
@Override
public double cost() {
return 0.20 + beverage.cost();
}
}
public class StarbuzzCoffee {
public static void main(String[] args){
Beverage beverage = new Espresso();
System.out.println(beverage.getDescription() + " $ "+beverage.cost());
beverage = new Mocha(beverage);
System.out.println(beverage.getDescription() + " $ "+beverage.cost());
}
}原文:http://3540931.blog.51cto.com/3530931/1874325