装饰模式可以在不创造更多的子类的模式下,将对象的功能加以扩展。
在java,io 中就有用到了很多装饰者模式。
所有的类都继承了 InputStream 这个类,同时在他们的构造方法中 都有一个 InputStream 对象作为参数。
我们常见的:
BufferedInputStream bufferedInputStream=new BufferedInputStream(new FileInputStream(file));
可以这样看,FileInputStream 读的 在经过BufferedInputStream 装饰 的到BufferedInputStream 其实也是继承于 InoutStream的。
下面看些实例:
/** * 所有饮料的 父类 * */ public abstract class Beverage { protected String description; /** * 饮料的描述 * @return */ public String getDescription() { return description; } /** * 计算 价格 * @return */ public abstract double cost(); }
/** * 装饰者 此处是所有 调料的父类 */ public abstract class CondimentDecorator extends Beverage { /** * 所有的调料都必须是现该方法 */ public abstract String getDescription(); }
public class Milk extends CondimentDecorator{ private Beverage beverage; public Milk(Beverage beverage){ this.beverage = beverage; } @Override public String getDescription() { return beverage.getDescription() + ", milk"; } @Override public double cost() { return beverage.cost() + .10; } }
/** * 摩卡 */ public class Mocha extends CondimentDecorator{ private Beverage beverage; public Mocha(Beverage beverage){ this.beverage = beverage; } @Override public String getDescription() { return beverage.getDescription() + ", mocha"; } @Override public double cost() { return beverage.cost() + .20; } }
public class Whip extends CondimentDecorator { private Beverage beverage; public Whip(Beverage beverage) { this.beverage = beverage; } @Override public String getDescription() { return beverage.getDescription() + ", whip"; } @Override public double cost() { return beverage.cost() + .10; } }
/** * 豆浆 */ public class Soy extends CondimentDecorator{ private Beverage beverage; public Soy(Beverage beverage){ this.beverage = beverage; } @Override public String getDescription() { return beverage.getDescription() + ", soy"; } @Override public double cost() { return beverage.cost() + .15; } }
/** * 浓咖啡 */ public class Espresso extends Beverage{ public Espresso(){ description = "Espresso"; } @Override public double cost() { return 1.99; } }
/** * 星巴克 独家首选咖啡 */ public class HouseBlend extends Beverage{ public HouseBlend(){ description = "HouseBlend"; } @Override public double cost() { return .89; } }
public class Main { public static void main(String[] args) { Beverage beverage1 = new Espresso(); beverage1 = new Mocha(beverage1); beverage1 = new Mocha(beverage1); beverage1 = new Whip(beverage1); System.out .println(beverage1.getDescription() + " $" + beverage1.cost()); Beverage beverage2 = new HouseBlend(); beverage2 = new Soy(beverage2); beverage2 = new Whip(beverage2); System.out.println(beverage2.getDescription() + " $ " + beverage2.cost()); } }