相关文章
【合集】Java设计模式
装饰者模式
其实就是继承抽象构件,又组合了一个抽象构件
抽象构件-饮品
1
2
3
4
5
6
7
|
@Getter
@AllArgsConstructor
public abstract static class Drink {
private String des;
private float price;
public abstract float cost();
}
|
抽象构件-饮品(继承饮品)
1
2
3
4
5
6
7
8
9
|
public static class Coffee extends Drink {
public Coffee(String des, float price) {
super(des, price);
}
@Override
public float cost() {
return super.price;
}
}
|
具体构件-美式咖啡
1
2
3
4
5
|
public static class LongBlack extends Coffee {
public LongBlack() {
super("longBlack", 5.0f);
}
}
|
具体构件-意大利咖啡
1
2
3
4
5
|
public static class Espresso extends Coffee {
public Espresso() {
super("意大利咖啡", 6.0f);
}
}
|
装饰抽象类
其实就是继承抽象构件,又组合了一个抽象构件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public static class Decorator extends Drink {
private final Drink obj;
public Decorator(Drink obj, String des, float price) {
super(des, price);
this.obj = obj;
}
@Override
public float cost() {
return super.price + obj.cost();
}
@Override
public String getDes() {
return super.des + obj.getDes();
}
}
|
具体装饰类-巧克力
1
2
3
4
5
|
public static class Chocolate extends Decorator {
public Chocolate(Drink obj) {
super(obj, "巧克力", 3.0f);
}
}
|
具体装饰类-牛奶
1
2
3
4
5
|
public static class Milk extends Decorator {
public Milk(Drink obj) {
super(obj, "牛奶", 2.0f);
}
}
|
具体装饰类-豆浆
1
2
3
4
5
|
public static class Soy extends Decorator {
public Soy(Drink obj) {
super(obj, "豆浆", 1.5f);
}
}
|
客户端调用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
Drink order = new LongBlack();
order = new Milk(order);
System.out.println(order.getDes() + " " + order.cost() + "元");
order = new Chocolate(order);
System.out.println(order.getDes() + " " + order.cost() + "元");
order = new Chocolate(order);
System.out.println(order.getDes() + " " + order.cost() + "元");
System.out.println("===========================");
Drink order2 = new Soy(order);
System.out.println(order2.getDes() + " " + order2.cost() + "元");
order2 = new Milk(order2);
System.out.println(order2.getDes() + " " + order2.cost() + "元");
|
输出
1
2
3
4
5
6
|
牛奶longBlack 7.0元
巧克力牛奶longBlack 10.0元
巧克力巧克力牛奶longBlack 13.0元
===========================
豆浆巧克力巧克力牛奶longBlack 14.5元
牛奶豆浆巧克力巧克力牛奶longBlack 16.5元
|
应用
1
2
3
4
|
应用:{@link java.io.FilterInputStream}装饰角色就是继承了InputStream, 并且组合了InputStream, {@link java.io.BufferedInputStream}则是具体装饰角色
应用:{@link java.io.InputStreamReader}装饰角色就是继承了Reader, 并且组合了StreamDecoder,{@link java.io.FileReader}则是具体装饰角色
应用:{@link java.io.BufferedReader}装饰角色就是继承了Reader, 并且组合了Reader
应用:{@link java.io.OutputStreamWriter}装饰角色就是继承了Writer, 并且组合了StreamEncoder,{@link java.io.FileWriter}则是具体装饰角色
|
文件输入流
装饰角色:java.io.FilterInputStream
被装饰的接口:InputStream