组合模式是将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
【示例】对象的组合
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
|
class Cpu { public void run() { System.out.println( "quickly........." ); } } class MainBoard { public void connect() { System.out.println( "connect..........." ); } } class Memory { public void store() { System.out.println( "store........" ); } } public class Computer { Cpu cpu; Memory memory; MainBoard mainBoard; public void work() { cpu.run(); memory.store(); mainBoard.connect(); } public static void main(String[] args) { Computer computer = new Computer(); computer.cpu = new Cpu(); computer.mainBoard = new MainBoard(); computer.memory = new Memory(); computer.work(); } } |