[Java] Java设计模式 外观模式建模与实现 →→→→→进入此内容的聊天室

来自 , 2020-06-02, 写在 Java, 查看 163 次.
URL http://www.code666.cn/view/7d771e0e
  1. /**
  2.  * 示例:外观模式,也称门面模式
  3.  *
  4.  * 优点:为了解决类与类之间的依赖关系,降低了类与类之间的耦合度
  5.  *
  6.  * 该模式中没有涉及到接口
  7.  */
  8.  
  9. class Memory {
  10.         public void startup() {
  11.                 System.out.println("this is memory startup...");
  12.         }
  13.  
  14.         public void shutdown() {
  15.                 System.out.println("this is memory shutdown...");
  16.         }
  17.  
  18. }
  19.  
  20. class CPU {
  21.         public void startup() {
  22.                 System.out.println("this is CPU startup...");
  23.         }
  24.  
  25.         public void shutdown() {
  26.                 System.out.println("this is CPU shutdown...");
  27.         }
  28. }
  29.  
  30. /**
  31.  * 作为facade,持有Memory、CPU的实例
  32.  *
  33.  * 任务让Computer帮咱们处理,我们无需直接和Memory、CPU打交道
  34.  *
  35.  * 这里有点像去商店里买东西:咱们买东西只需要到商店去买,而无需去生产厂家那里买。
  36.  *
  37.  * 商店就可以称为是一个facade外观(门面)模式。--> 商品都在商店里
  38.  */
  39. class Computer {
  40.         private Memory memory;
  41.         private CPU cpu;
  42.  
  43.         public Computer() {
  44.                 memory = new Memory();
  45.                 cpu = new CPU();
  46.         }
  47.  
  48.         public void startup() {
  49.                 System.out.println("begin to start the computer...");
  50.                 memory.startup();
  51.                 cpu.startup();
  52.                 System.out.println("computer start finished...");
  53.         }
  54.  
  55.         public void shutdown() {
  56.                 System.out.println("begin to close the computer...");
  57.                 memory.shutdown();
  58.                 cpu.shutdown();
  59.                 System.out.println("computer close finished...");
  60.         }
  61. }
  62.  
  63. /**
  64.  * 客户端测试类
  65.  *
  66.  * @author Leo
  67.  */
  68. public class Test {
  69.         public static void main(String[] args) {
  70.                 Computer computer = new Computer();
  71.                 computer.startup();
  72.                 System.out.println("\n");
  73.                 computer.shutdown();
  74.         }
  75. }//源代码片段来自云代码http://yuncode.net
  76.                        

回复 "Java设计模式 外观模式建模与实现"

这儿你可以回复上面这条便签

captcha