外观模式(Facade)
外观模式是为了解决类与类之家的依赖关系的
像spring一样,可以将类和类之间的关系配置到配置文件中
而外观模式就是将他们的关系放在一个Facade类中
降低了类类之间的耦合度,该模式中没有涉及到接口
一、3个基础类模式
package Facade; public class CPU { public void startup(){ System.out.println("cpu 启动!"); } public void shutdown(){ System.out.println("cup 关闭"); } } package Facade; public class Memory { public void startup(){ System.out.println("内存 启动!"); } public void shutdown(){ System.out.println("内存 关闭"); } } package Facade; public class Disk { public void startup(){ System.out.println("硬盘 启动!"); } public void shutdown(){ System.out.println("硬盘 关闭"); } }
二、映射类关系(降低单元类之间的关系)
1 package Facade; 2 3 public class Computer { 4 private CPU cpu; 5 private Memory memory; 6 private Disk disk; 7 8 public Computer(){ 9 this.cpu = new CPU(); 10 this.memory = new Memory(); 11 this.disk = new Disk(); 12 } 13 public void startup(){ 14 System.out.println("start the computer...~"); 15 cpu.startup(); 16 memory.startup(); 17 disk.startup(); 18 System.out.println("start the computer finished!"); 19 } 20 public void shutdown(){ 21 System.out.println("shutdown the computer...~"); 22 cpu.shutdown(); 23 memory.shutdown(); 24 disk.shutdown(); 25 System.out.println("shutdown the computer finished!"); 26 } 27 28 }
三、客户端操作
1 package Facade; 2 3 public class User { 4 5 public static void main(String[] args) { 6 // TODO Auto-generated method stub 7 Computer cpu = new Computer(); 8 cpu.startup(); 9 cpu.shutdown(); 10 } 11 12 }
四、结果
1 start the computer...~ 2 cpu 启动! 3 内存 启动! 4 硬盘 启动! 5 start the computer finished! 6 shutdown the computer...~ 7 cup 关闭 8 内存 关闭 9 硬盘 关闭 10 shutdown the computer finished!
时间: 2024-10-13 06:55:26