外觀模式
- 外觀模式主要的功能是減少類與類之間的聯(lián)系,降低了類與類之間的耦合度酬诀。
public class CPU {
public void startup(){
System.out.println("cpu startup!");
}
public void shutdown(){
System.out.println("cpu shutdown!");
}
}
public class Memory {
public void startup(){
System.out.println("memory startup!");
}
public void shutdown(){
System.out.println("memory shutdown!");
}
}
public class Disk {
public void startup(){
System.out.println("disk startup!");
}
public void shutdown(){
System.out.println("disk shutdown!");
}
}
public class Computer {
private CPU cpu;
private Memory memory;
private Disk disk;
public Computer(){
cpu = new CPU();
memory = new Memory();
disk = new Disk();
}
public void startup(){
System.out.println("start the computer!");
cpu.startup();
memory.startup();
disk.startup();
System.out.println("start computer finished!");
}
public void shutdown(){
System.out.println("begin to close the computer!");
cpu.shutdown();
memory.shutdown();
disk.shutdown();
System.out.println("computer closed!");
}
}
測試類
public class User {
public static void main(String[] args) {
Computer computer = new Computer();
computer.startup();
computer.shutdown();
}
}
如果我們沒有Computer類曹质,那么婴噩,CPU、Memory咆繁、Disk他們之間將會相互持有實例讳推,產生關系,這樣會造成嚴重的依賴玩般,修改一個類银觅,可能會帶來其他類的修改,這不是我們想要看到的坏为,有了Computer類究驴,他們之間的關系被放在了Computer類里,這樣就起到了解耦的作用匀伏,這洒忧,就是外觀模式!