• 外观模式


           这个模式我理解是这样的,客户端直接和业务系统打交道太麻烦了,可能调用业务系统好多类,你业务系统能不能给我一个类,这个类里面封装了好多业务系统的其他功能,客户端掉的时候直接通过这个类就能完成。

    如图:

    使用前:

     

     使用后:

    定义:

    外观模式(Facade Pattern)隐藏系统的复杂性,并向客户端提供了一个客户端可以访问系统的接口。这种类型的设计模式属于结构型模式,它向现有的系统添加一个接口,来隐藏系统的复杂性。

    意图:

    为子系统中的一组接口提供一个一致的界面,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。

    主要解决:

    降低访问复杂系统的内部子系统时的复杂度,简化客户端与之的接口。

    何时使用: 

    1、客户端不需要知道系统内部的复杂联系,整个系统只需提供一个"接待员"即可。 2、定义系统的入口。

    如何解决:

    客户端不与系统耦合,外观类与系统耦合。

    关键代码:

    在客户端和复杂系统之间再加一层,这一层将调用顺序、依赖关系等处理好。

    应用实例:

     1、去医院看病,可能要去挂号、门诊、划价、取药,让患者或患者家属觉得很复杂,如果有提供接待人员,只让接待人员来处理,就很方便。 2、JAVA 的三层开发模式。

    优点: 

    1、减少系统相互依赖。 2、提高灵活性。 3、提高了安全性。

    缺点:

    不符合开闭原则,如果要改东西很麻烦,继承重写都不合适。

    使用场景: 

    1、为复杂的模块或子系统提供外界访问的模块。 2、子系统相对独立。 3、预防低水平人员带来的风险。

    注意事项:

    在层次化结构中,可以使用外观模式定义系统中每一层的入口。

    UML图:

     请看代码:

    步骤一:

    public interface Shape {
       void draw();
    }
    

    步骤2:

    public class Rectangle implements Shape {
     
       @Override
       public void draw() {
          System.out.println("Rectangle::draw()");
       }
    }
    public class Square implements Shape {
     
       @Override
       public void draw() {
          System.out.println("Square::draw()");
       }
    }
    public class Circle implements Shape {
     
       @Override
       public void draw() {
          System.out.println("Circle::draw()");
       }
    }

    步骤3(关键步骤啊,外观模式):

    public class ShapeMaker {
       private Shape circle;
       private Shape rectangle;
       private Shape square;
     
       public ShapeMaker() {
          circle = new Circle();
          rectangle = new Rectangle();
          square = new Square();
       }
     
       public void drawCircle(){
          circle.draw();
       }
       public void drawRectangle(){
          rectangle.draw();
       }
       public void drawSquare(){
          square.draw();
       }
    }

    步骤4(输出):

    public class FacadePatternDemo {
       public static void main(String[] args) {
          ShapeMaker shapeMaker = new ShapeMaker();
     
          shapeMaker.drawCircle();
          shapeMaker.drawRectangle();
          shapeMaker.drawSquare();      
       }
    }

    参考:https://www.runoob.com/design-pattern/facade-pattern.html

      

  • 相关阅读:
    RocketMQ 概念
    CentOS7使用firewalld管理防火墙
    java应用启动报错Unable to access jarfile xxxxx.jar
    docker启动redis并设置密码
    sql优化整理(二)
    sql优化整理(一)
    dubbo配置的覆盖关系
    dubbo配置加载优先级
    ZooKeeper的数据模型
    leetcode104:permutations
  • 原文地址:https://www.cnblogs.com/doumenwangjian/p/14120239.html
Copyright © 2020-2023  润新知