structure:装饰器模式 (Decorate Pattern) 3
- UID
- 1066743
|
structure:装饰器模式 (Decorate Pattern) 3
package Decorate;
public class TestDecorate {
public static void test(){
Beverage beverage=new Espresso();
System.out.println(beverage.getDescription()+" $"+beverage.cost());
Beverage beverage2=new DarkRoast();
beverage2=new Mocha(beverage2);
beverage2=new Mocha(beverage2);
beverage2=new Whip(beverage2);
System.out.println(beverage2.getDescription()+" $"+beverage2.cost());
Beverage beverage3=new HouseBlend();
beverage3=new Soy(beverage3);
beverage3=new Mocha(beverage3);
beverage3=new Whip(beverage3);
System.out.println(beverage3.getDescription()+" $"+beverage3.cost());
}
}
package Decorate;
/*
奶泡
*/
public class Whip extends CondimentDecorator {
Beverage beverage;
public Whip(Beverage beverage) {
this.beverage = beverage;
}
//描述完整的调用过程
@Override
public String getDescription() {
return beverage.getDescription()+", Whip";
}
@Override
public double cost() {
return 0.30+beverage.cost();
}
}
引申学习:
java 里的java.io 类数量庞大,但是也是利用了装饰者模式创建的,理解装饰者模式,就能理解大量的io类。
比如InputStream类,相当于beverage。
FileInputstream、StringBufferInputStream、ByteArrayInputStream相当于具体的饮料,都继承自InputStream(beverage)。
FileterInputStream相当于CondimentDecorate,继承自InputStream(beverage)而
该类的子类PushbackInputStream、BufferedInputStream、DataInputStream、LineNumberInputStream相当于调料类,也都继承自FilterInputStream(CondimentDecorate)。
我们可以利用装饰器模式,创建自己的I/O 装饰者。
继承FileterInputStream,然后在构造方法里面组合需要用的FileterInputStream的子类的功能。 |
|
|
|
|
|