• 设计模式外观模式


    外观模式
      定义: 隐藏了系统的复杂性,并向客户端提供了一个可以访问系统的接口。

    1.1 模式结构和代码示例


      简单来说,该模式就是把一些复杂的流程封装成一个接口供给外部用户更简单的使用。这个模式中,设计到3个角色。

        1).门面角色:外观模式的核心。它被客户角色调用,它熟悉子系统的功能。内部根据客户角色的需求预定了几种功能的组合。(客户调用,同时自身调用子系统功能)

        2).子系统角色:实现了子系统的功能。它对客户角色和Facade时未知的。它内部可以有系统内的相互交互,也可以由供外界调用的接口。(实现具体功能)

        3).客户角色:通过调用Facede来完成要实现的功能(调用门面角色)。

      举例(每个Computer都有CPU、Memory、Disk。在Computer开启和关闭的时候,相应的部件也会开启和关闭),类图如下:

     

      首先是子系统类:

        public class CPU {
          public void start() {
            System.out.println("cpu is start...");
          }

        public void shutDown() {
            System.out.println("CPU is shutDown...");
          }
        }

        public class Disk {
          public void start() {
            System.out.println("Disk is start...");
          }

          public void shutDown() {
            System.out.println("Disk is shutDown...");
          }
        }

        public class Memory {
          public void start() {
            System.out.println("Memory is start...");
          }

          public void shutDown() {
            System.out.println("Memory is shutDown...");
          }
        }
      然后是,门面类Facade

      public class Computer {

        private CPU cpu;
        private Memory memory;
        private Disk disk;

        public Computer() {
        cpu = new CPU();
        memory = new Memory();
        disk = new Disk();
      }

      public void start() {
        System.out.println("Computer start begin");
        cpu.start();
        disk.start();
        memory.start();
        System.out.println("Computer start end");
      }

      public void shutDown() {
        System.out.println("Computer shutDown begin");
        cpu.shutDown();
        disk.shutDown();
        memory.shutDown();
        System.out.println("Computer shutDown end...");
        }
      }  
      最后为,客户角色

      public class Client {
        public static void main(String[] args) {
          Computer computer = new Computer();
          computer.start();
          System.out.println("=================");
          computer.shutDown();
        } 
      }
    1.2 优点
      - 松散耦合

      使得客户端和子系统之间解耦,让子系统内部的模块功能更容易扩展和维护;

      - 简单易用

      客户端根本不需要知道子系统内部的实现,或者根本不需要知道子系统内部的构成,它只需要跟Facade类交互即可。

      - 更好的划分访问层次

     有些方法是对系统外的,有些方法是系统内部相互交互的使用的。子系统把那些暴露给外部的功能集中到门面中,这样就可以实现客户端的使用,很好的隐藏了子系统内部的细节。

  • 相关阅读:
    ios-点击图片放大,背景变半透明
    为代码分段标识
    方法的标签_With携带
    使用json要导入什么包
    Json中不支持任何形式的注释,那我们要怎么解决呢
    JFinal中文件上传后会默认放置到WebContent的upload包下,但是tomcat会自动重启,当我们再次打开upload文件夹查看我们刚刚上传的文件时,发现上传的文件已经没有了。
    JFinal上传文件时用getFile()方法报错
    JFinal文件上传时直接使用getPara()去接受表单的数据接收到的数据一直是null?
    Freemarker全部文档和具体实例
    Eclipse安装Freemarker插件
  • 原文地址:https://www.cnblogs.com/zwbsoft/p/16202836.html
Copyright © 2020-2023  润新知