外观模式-Facade

外观模式是为了解决类与类之间依赖关系的,外观模式将类间关系放在一个Facade类中,降低了类类之间的耦合度,该模式中不涉及接口
构造外观模式 举一个经典的例子:
  • CPU
public class CPU { public void startup(){ System.out.println("cpu startup"); }public void shutdown(){ System.out.println("cpu shutdown"); } }

  • Mainboard
public class Mainboard {public void startup(){ System.out.println("mainboard startup"); }public void shutdown(){ System.out.println("mainboard shutdown"); } }

  • Disk
public class Disk {public void startup(){ System.out.println("disk startup"); }public void shutdown(){ System.out.println("disk shutdown"); } }

  • Computer类(外观类)
public class Computer { private CPU cpu; private Mainboard mainboard; private Disk disk; public Computer(){ cpu = new CPU(); mainboard = new Mainboard(); disk = new Disk(); }public void startup(){ System.out.println("starting the computer"); cpu.startup(); mainboard.startup(); disk.startup(); System.out.println("computer is started"); }public void shutdown(){ System.out.println("closing the computer"); disk.shutdown(); mainboard.shutdown(); cpu.shutdown(); System.out.println("computer is closed"); } }

测试
public class Main {public static void main(String[] args) { Computer computer = new Computer(); computer.startup(); computer.shutdown(); } }

测试结果:
starting the computer
cpu startup
mainboard startup
disk startup
computer is started
closing the computer
disk shutdown
mainboard shutdown
cpu shutdown
computer is closed
分析
【外观模式-Facade】如果我们没有外观类(Computer),CPU、Mainboard、Disk之间将会相互持有实例对象,造成严重的依赖;而有了Computer,他们之间的关系被放在了Computer类里,这样就起到了解耦的作用。这就是外观模式!

    推荐阅读