外观模式

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

举例(每个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();
    }
 
}

优点
  - 松散耦合

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

  - 简单易用

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

  - 更好的划分访问层次

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

posted on 2021-10-19 22:36  季昂  阅读(46)  评论(0编辑  收藏  举报