设计模式之装饰模式

定义

1
2
3
装饰模式(Decorator Pattern): 动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
注:装饰模式是利用SetComponent 来对对象进行包装的,不需要关心如何被添加到对象链种。
个人理解:就是将一些额外的功能独立出来

优点

1
2
3
可以在不修改现有代码的情况下,动态地添加新功能。
可以将多个装饰器组合使用,以实现更复杂的功能组合。
遵循开闭原则,对扩展开放,对修改关闭

代码解释

1
2
3
4
5
Coffee 接口定义了基本的组件接口,包含 getCost() 和 getDescription() 方法。
SimpleCoffee 类是具体组件,实现了 Coffee 接口。
CoffeeDecorator 是一个抽象装饰器类,它也实现了 Coffee 接口,并持有一个 Coffee 对象。
MilkDecorator 和 SugarDecorator 是具体的装饰器,它们扩展了 CoffeeDecorator,并在原有咖啡的基础上添加了新的行为(增加成本和描述)。
在 main 方法中,我们展示了如何使用这些装饰器来动态地创建不同种类的咖啡。

代码

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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// 基础接口
interface Coffee {
double getCost();
String getDescription();
}

// 具体组件
class SimpleCoffee implements Coffee {
@Override
public double getCost() {
return 1;
}

@Override
public String getDescription() {
return "Simple coffee";
}
}

// 装饰器抽象类
abstract class CoffeeDecorator implements Coffee {
protected Coffee decoratedCoffee;

public CoffeeDecorator(Coffee coffee) {
this.decoratedCoffee = coffee;
}

public double getCost() {
return decoratedCoffee.getCost();
}

public String getDescription() {
return decoratedCoffee.getDescription();
}
}

// 具体装饰器
class MilkDecorator extends CoffeeDecorator {
public MilkDecorator(Coffee coffee) {
super(coffee);
}

@Override
public double getCost() {
return super.getCost() + 0.5;
}

@Override
public String getDescription() {
return super.getDescription() + ", milk";
}
}

class SugarDecorator extends CoffeeDecorator {
public SugarDecorator(Coffee coffee) {
super(coffee);
}

@Override
public double getCost() {
return super.getCost() + 0.2;
}

@Override
public String getDescription() {
return super.getDescription() + ", sugar";
}
}

// 主类
public class DecoratorPatternDemo {
public static void main(String[] args) {
Coffee simpleCoffee = new SimpleCoffee();
System.out.println("Cost: " + simpleCoffee.getCost() + "; Description: " + simpleCoffee.getDescription());

Coffee milkCoffee = new MilkDecorator(simpleCoffee);
System.out.println("Cost: " + milkCoffee.getCost() + "; Description: " + milkCoffee.getDescription());

Coffee sweetMilkCoffee = new SugarDecorator(new MilkDecorator(new SimpleCoffee()));
System.out.println("Cost: " + sweetMilkCoffee.getCost() + "; Description: " + sweetMilkCoffee.getDescription());
}
}