文章目录
  1. 组合模式

组合模式

  • 将对象组合成树形结构以表示“部分-整体”的层次结构。使得对单个对象和组合对象的使用具有一致性。
    Composite
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
83
84
85
86
87
88
89
90
91
92
93
94
public interface IMoudle {
String getName();
void add(IMoudle moudle);
void remove(IMoudle moudle);
int totalPrice();
}
public class Moudle implements IMoudle {
private String name;
private int price;
private List<IMoudle> childrenMoudleList;
public Moudle(int price, String name) {
this.name = name;
this.price = price;
childrenMoudleList = new ArrayList<>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void add(IMoudle moudle) {
childrenMoudleList.add(moudle);
}
@Override
public void remove(IMoudle moudle) {
childrenMoudleList.remove(moudle);
}
public int totalPrice() {
if (CollectionUtils.isEmpty(childrenMoudleList)) {
return price;
}
return price+childrenMoudleList.stream().collect(Collectors.summingInt(IMoudle::totalPrice));
}
}
public class Battery extends Moudle{
public Battery(int price, String name) {
super(price,name);
}
}
public class CPU extends Moudle {
public CPU(int price, String name) {
super(price,name);
}
}
public class EarPhone extends Moudle{
public EarPhone(int price, String name) {
super(price,name);
}
}
public class Memory extends Moudle{
public Memory(int price, String name) {
super(price,name);
}
}
public class Phone extends Moudle{
public Phone(int price, String name) {
super(price,name);
}
}
public class App {
public static void main(String[] args) {
IMoudle phone=new Phone(100,"Iphone");
IMoudle earPhone=new EarPhone(200,"Earphone");
IMoudle cpu=new CPU(300,"cpu A8");
IMoudle memory=new Memory(400,"cpu A8");
IMoudle battery=new Battery(500,"battery");
cpu.add(memory);
phone.add(cpu);
phone.add(earPhone);
phone.add(battery);
phone.add(phone);
phone.remove(phone);
System.out.println(phone.totalPrice());
}
}
文章目录
  1. 组合模式