外观模式
Table of Contents
外观模式是为了解决类与类之间的依赖关系的,将他们的关系放在一个Facade类中,降低了类与类之间的耦合度
UML
Java
- 编写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!"); } }
- 编写Computer类来简化客户端调用:
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 ComputerTest { public static void main(String[] args) { Computer computer = new Computer(); computer.startup(); System.out.println(); computer.shutdown(); } }
- 测试结果:
start the computer! cpu startup! memory startup! disk startup! start computer finished! begin to close the computer! cpu shutdown! memory shutdown! disk shutdown! computer closed!
Racket/Common-Lisp
函数式编程往往使用module或者package来模块化代码:
- 通过宏把函数编译到module或者package中
- 客户端通过import module/require package来进行调用