zoukankan      html  css  js  c++  java
  • java外观模式

    外观模式是为了解决类与类之家的依赖关系的,像spring一样,可以将类和类之间的关系配置到配置文件中,而外观模式就是将他们的关系放在一个Facade类中,降低了类类之间的耦合度,该模式中没有涉及到接口,看下类图:(我们以一个计算机的启动过程为例)

    我们先看下实现类:

    1. public class CPU {  
    2.       
    3.     public void startup(){  
    4.         System.out.println("cpu startup!");  
    5.     }  
    6.       
    7.     public void shutdown(){  
    8.         System.out.println("cpu shutdown!");  
    9.     }  
    10. }  
    1. public class Memory {  
    2.       
    3.     public void startup(){  
    4.         System.out.println("memory startup!");  
    5.     }  
    6.       
    7.     public void shutdown(){  
    8.         System.out.println("memory shutdown!");  
    9.     }  
    10. }  
    1. public class Disk {  
    2.       
    3.     public void startup(){  
    4.         System.out.println("disk startup!");  
    5.     }  
    6.       
    7.     public void shutdown(){  
    8.         System.out.println("disk shutdown!");  
    9.     }  
    10. }  
    1. public class Computer {  
    2.     private CPU cpu;  
    3.     private Memory memory;  
    4.     private Disk disk;  
    5.       
    6.     public Computer(){  
    7.         cpu = new CPU();  
    8.         memory = new Memory();  
    9.         disk = new Disk();  
    10.     }  
    11.       
    12.     public void startup(){  
    13.         System.out.println("start the computer!");  
    14.         cpu.startup();  
    15.         memory.startup();  
    16.         disk.startup();  
    17.         System.out.println("start computer finished!");  
    18.     }  
    19.       
    20.     public void shutdown(){  
    21.         System.out.println("begin to close the computer!");  
    22.         cpu.shutdown();  
    23.         memory.shutdown();  
    24.         disk.shutdown();  
    25.         System.out.println("computer closed!");  
    26.     }  
    27. }  

    User类如下:

    1. public class User {  
    2.   
    3.     public static void main(String[] args) {  
    4.         Computer computer = new Computer();  
    5.         computer.startup();  
    6.         computer.shutdown();  
    7.     }  
    8. }  

    输出:

    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!

    如果我们没有Computer类,那么,CPU、Memory、Disk他们之间将会相互持有实例,产生关系,这样会造成严重的依赖,修改一个类,可能会带来其他类的修改,这不是我们想要看到的,有了Computer类,他们之间的关系被放在了Computer类里,这样就起到了解耦的作用,这,就是外观模式!

  • 相关阅读:
    【codevs1690】开关灯 (线段树 区间修改+区间求和 (标记))
    【codevs1191】数轴染色 (线段树 区间修改+固定区间查询)
    【机器学习】李航 统计学习方法 知识点总结
    【机器学习】生成模型 判别模型
    【机器学习】贝叶斯定理、精准推断、最大似然估计、连续特征参数估计、EM算法
    python queue 讲解
    【tensorflow】 CNN卷积神经网络原理讲解+图片识别应用(附源码)
    URL解析过程
    Python 可迭代对象迭代器生成器的区别
    【Linux】 修改主机名
  • 原文地址:https://www.cnblogs.com/fan-yuan/p/7989232.html
Copyright © 2011-2022 走看看