外观模式的作用:
外观模式的角色:
实例探究
假设一台电脑,它包含了 CPU(处理器),Memory(内存) ,Disk(硬盘)这几个部件,若想要启动电脑,则先后必须启动 CPU、Memory、Disk。关闭也是如此。
但是实际上我们在电脑开/关机时根本不需要去操作这些组件,因为电脑已经帮我们都处理好了,并隐藏了这些东西。
这些组件好比子系统角色,而电脑就是一个外观角色。
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!");
}
}
具体调用如下:
Computer computer = new Computer();
computer.startup();
computer.shutdown();