JAVA设计模式之外观模式

149 阅读1分钟

本文介绍23种设计模式之外观模式。

定义

提供一个统一的接口,用来访问子系统中的一群接口,外观定义了一个高层接口,让子系统更容易使用。 简单来说就是通过门面作为对外的访问入口,减少关联对象,降低耦合度。

描述

  • 模式名称:FACADE(外观)
  • 类型:对象结构型模式
  • 意图:为子系统中的一组接口提供一个一致的界面, Facade模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
  • 适用性:
    • 当你要为一个复杂子系统提供一个简单接口时。
  • 效果:
  • 优点:
    • 降低客户与子系统之间的耦合度。
    • 提高灵活性和安全度。
  • 缺点:
    • 不符合开闭原则,如果要改东西很麻烦,继承重写都不合适。

类图

1629344204(1).png

  1. 客户(Client):通过一个外观角色访问各个子系统的功能。
  2. 外观(Facade):为多个子系统对外提供一个共同的接口。
  3. 关联对象(product):实现功能的对象,客户可以通过外观角色访问它。

实现代码

Facade

public class HomeTheaterFacade {
    Amplifier amplifier;
    Tuner tuner;
    DvdPlayer dvdPlayer;

    public HomeTheaterFacade(Amplifier amplifier, Tuner tuner, DvdPlayer dvdPlayer) {
        this.amplifier = amplifier;
        this.tuner = tuner;
        this.dvdPlayer = dvdPlayer;
    }

    public void watchMovie(){
        tuner.on();
        amplifier.on();
        amplifier.setDVD(dvdPlayer);
        amplifier.setSurroundSound();
        dvdPlayer.on();
        dvdPlayer.play();
    }


}

Client

public class Client {
    public static void main(String[] args) {
        HomeTheaterFacade homeTheaterFacade = new HomeTheaterFacade(new Amplifier(), new Tuner(), new DvdPlayer());
        homeTheaterFacade.watchMovie(); //客户端只需调研facade即可,不用管内部的处理逻辑
    }
}