设计模式之装饰者模式
设计模式 Java About 2,169 words作用
动态的将新功能附加到对象上。在对象功能扩展方面,它比继承更有弹性,装饰者模式也体现了开闭原则(OCP)。
原理
打包快递。
主体-被装饰者:陶瓷、衣服
包装-装饰者:纸板、塑料袋
案例
装饰者继承被装饰者,并且聚合被装饰者。
被装饰者
public abstract class Drink {
private String desc;
private float price;
public abstract float cost();
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
装饰者
public class Decorator extends Drink {
private Drink drink;
public Decorator(Drink drink) {
this.drink = drink;
}
@Override
public float cost() {
return getPrice() + drink.cost();
}
}
被装饰者缓冲层
public class Coffee extends Drink {
@Override
public float cost() {
return getPrice();
}
}
具体被装饰者
浓咖啡
public class Espresso extends Coffee {
public Espresso() {
setDesc("浓咖啡");
setPrice(6f);
}
}
美式咖啡
public class LongBlack extends Coffee {
public LongBlack() {
setDesc("美式咖啡");
setPrice(4f);
}
}
具体装饰者
牛奶
public class Milk extends Decorator {
public Milk(Drink drink) {
super(drink);
setDesc("牛奶");
setPrice(2f);
}
}
豆浆
public class Soy extends Decorator {
public Soy(Drink drink) {
super(drink);
setDesc("豆浆");
setPrice(1.5f);
}
}
使用
public class CoffeeBar {
public static void main(String[] args) {
Drink order = new Espresso();
System.out.println(order.cost());
Drink order2 = new Milk(new Espresso());
System.out.println(order2.cost());
Drink order3 = new Soy(new Milk(new Milk(new Espresso())));
System.out.println(order3.cost());
}
}
源码
关系
分析
- InputStream是抽象类,类似案例中的Drink。
- FileInputStream是InputStream的子类,类似案例中的Espresso、LongBlack。
- FilterInputStream是InputStream的子类且聚合了被装饰者InputStream(
protected volatile InputStream in;
),类似案例中的Decorator。 - BufferedInputStream是FilterInputStream的子类,类似案例中的Milk、Soy。
应用
BufferedInputStream br = new BufferedInputStream(new FileInputStream("README.md"));
System.out.println(br.read());
br.close();
Views: 2,475 · Posted: 2019-12-18
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...