设计模式之外观模式

157 阅读1分钟

一、概述

  • 外观模式(Facade),也称为“过程模式”。外观模式为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
  • 外观模式通过定义一个一致的接口,用以屏蔽内部子系统的细节,使得调用端只需跟这个接口发生调用,而无需关心这个子系统的内部细节
  • 外观模式对外屏蔽了子系统的细节,因此外观模式降低了客户端对子系统使用的复杂性
  • 外观模式对客户端和子系统的耦合关系进行解耦,让子系统内部的模块更易维护和拓展
  • 通过合理的使用外观模式,可以帮我们更好的划分访问的层次
  • 当维护一个遗留的大型系统时,可能这个系统已经变得非常难以维护和拓展,此时可以考虑为新系统开发一个Facade类,来提供遗留系统的比较清晰简单的接口,让新系统与Facade类交互,提高复用性
  • 就相当于,封了一个黑盒子,只对外暴露一些简单的接口

二、家庭影院项目

在这里插入图片描述

public enum TheaterLight {
  INSTANCE;

  public static TheaterLight getInstance() {
    return INSTANCE;
  }

  public void on() {
    System.out.println("Theater on!");
  }

  public void off() {
    System.out.println("Theater off!");
  }

  public void dim() {
    System.out.println("Theater dim!");
  }

  public void bright() {
    System.out.println("Theater bright!");
  }
}
public enum DVDPlayer {
  INSTANCE;

  public static DVDPlayer getInstance() {
    return INSTANCE;
  }

  public void on() {
    System.out.println("DVD on");
  }

  public void off() {
    System.out.println("DVD off");
  }

  public void pause() {
    System.out.println("DVD pause");
  }

  public void play() {
    System.out.println("DVD is playing");
  }
}
public class HomeTheaterFacade {
  private DVDPlayer dVDPlayer;
  private TheaterLight theaterLight;

  public HomeTheaterFacade() {
    dVDPlayer = DVDPlayer.getInstance();
    theaterLight = TheaterLight.getInstance();
  }

  public void on() {
    theaterLight.off();
    dVDPlayer.on();
  }

  public void off() {
    theaterLight.on();
    dVDPlayer.off();
  }
}
public class Client {
  public static void main(String[] args) {
    HomeTheaterFacade homeTheaterFacade = new HomeTheaterFacade();
    homeTheaterFacade.on();
    homeTheaterFacade.off();
  }
}