文章目录
  1. 装饰模式

装饰模式

  • 动态地给一个对象添加一些额外的职责。就增加功能来说,相比生成子类更加灵活
    Decorator
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
public interface IMoudle {
void build();
}
public class PhoneFrame implements IMoudle {
@Override
public void build() {
System.out.println("构建手机基础框架");
}
}
//装饰器模块的父类
public class DecoratorMoudle implements IMoudle {
protected IMoudle imoudle;
public DecoratorMoudle(IMoudle moudle){
imoudle=moudle;
}
@Override
public void build() {
System.out.println("doingNothind");
}
}
public class Battery extends DecoratorMoudle {
private int mAh;
public Battery(IMoudle targetMoudle, Integer mAh) {
super(targetMoudle);
this.mAh = mAh;
}
@Override
public void build() {
imoudle.build();
System.out.println("接入电池完成,容量:" + mAh+"mAH");
}
}
public class CPU extends DecoratorMoudle {
private String cpuName;
public CPU(IMoudle targetMoudle, String cpuName) {
super(targetMoudle);
this.cpuName = cpuName;
}
@Override
public void build() {
imoudle.build();
System.out.println("接入CPU完成,型号:" + cpuName);
}
}
public class App {
public static void main(String[] args) {
IMoudle phone = new Battery(new CPU(new PhoneFrame(), "A8"), 5000);
phone.build();
System.out.println("phone构建完毕");
}
}
文章目录
  1. 装饰模式