学习是件开心事

装饰者模式

对已有的业务逻辑进一步的封装,使其增加额外的功能,用户在使用的时候可以任意组装,达到自己想要的效果。如java中的io流。

设计的时候需要设计若干个同等级的子类,这些平行的子类都继承自同一个父类,并且有入参为父类的构造方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class Food {
private String name;
public Food() {
}
public Food(String name) {
this.name = name;
}
public String make() {
return name;
}
}
public class Bread extends Food {
private Food basic_food;
public Bread(Food basic_food) {
this.basic_food = basic_food;
}
public String make() {
return basic_food.make() + "+面包";
}
}
public class Cream extends Food {
private Food basic_food;
public Cream(Food basic_food) {
this.basic_food = basic_food;
}
public String make() {
return basic_food.make() + "+奶油";
}
}
public class Vegetable extends Food {
private Food basic_food;
public Vegetable(Food basic_food) {
this.basic_food = basic_food;
}
public String make() {
return basic_food.make()+ "+蔬菜";
}
}

测试类和运行结果为

1
2
3
4
5
public static void main(String[] args) {
Food food = new Bread(new Vegetable(new Cream(new Food("香肠"))));
System.out.println(food.make());
}

1
香肠+奶油+蔬菜+面包