• 结构型模式-外观模式


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

    这种模式涉及到一个单一的类,该类提供了客户端请求的简化方法和对现有系统类方法的委托调用。

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

    主要解决:降低访问复杂系统的内部子系统时的复杂度,简化客户端之间的接口。

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

    如何解决:客户端不与系统耦合,外观类与系统耦合。

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

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

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

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

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

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

    1. public interface Shape {
    2. void draw();
    3. }
    4. public class Circle implements Shape{
    5. @Override
    6. public void draw() {
    7. System.out.println("this is Circle.draw");
    8. }
    9. }
    10. public class Rectangle implements Shape{
    11. @Override
    12. public void draw() {
    13. System.out.println("this is Rectangle.draw");
    14. }
    15. }
    16. public class Square implements Shape{
    17. @Override
    18. public void draw() {
    19. System.out.println("this is Square.draw");
    20. }
    21. }
    1. public class ShapeMaker {
    2. private Shape circle;
    3. private Shape rectangle;
    4. private Shape square;
    5. public ShapeMaker() {
    6. circle = new Circle() ;
    7. rectangle = new Rectangle();
    8. square = new Square();
    9. }
    10. public void drawCircle(){
    11. circle.draw();
    12. }
    13. public void drawRectangle(){
    14. rectangle.draw();
    15. }
    16. public void drawSquare(){
    17. square.draw();
    18. }
    19. }
    1. @Test
    2. public void test7(){
    3. ShapeMaker shapeMaker = new ShapeMaker();
    4. shapeMaker.drawCircle();
    5. shapeMaker.drawRectangle();
    6. shapeMaker.drawSquare();
    7. }
    8. /*
    9. this is Circle.draw
    10. this is Rectangle.draw
    11. this is Square.draw
    12. */

  • 相关阅读:
    数据库基础知识详解五:MySQL中的索引和其两种引擎、主从复制以及关系型/非关系型数据库
    Linux:Mac VMware Fusion13以及CentOS7安装包
    SOFAJRaft与BRaft:打造稳定高效的分布式一致性架构
    c==ubuntu+vscode debug redis7源码
    基于RHEL 8的Linux发行版的初始服务器设置
    Day721. 外部函数接口 -Java8后最重要新特性
    欢迎初识MongoDB
    隐马尔可夫过程
    linux安装mysql
    Android数据结构和算法总结-字符串相关高频面试题算法
  • 原文地址:https://blog.csdn.net/weixin_44233087/article/details/132842210