基本介绍
外观模式(Facade),也叫过程模式,主要是为一组接口提供一个一致的“界面”,也就是定义一个更高层的接口,来对这一组接口进行统一的调度。这个接口使得者一组接口更容易使用。
外观模式通过定义一个一致的接口,就可以屏蔽这一组子接口的内部细节,使得调用防只需跟这个外观接口交互,而无需关系内部细节。
例子:
一个家庭私人影院有 爆米花机、DVD播放器、屏幕、影院灯光等,每一个都有操作开关,那一个个使用比较麻烦,且他们的操作都有一定的先后顺序,可以组合起来,于是给他们定义一个外观类。本质就是为了实现内聚
DVD播放器类:
public class DVDPlayer {
//使用单例模式
private static DVDPlayer instance = new DVDPlayer();
public static DVDPlayer getInstance(){
return instance;
}
public void on(){
System.out.println("dvd on ");
}
public void off(){
System.out.println("dvd off");
}
public void play(){
System.out.println("dvd is playing");
}
public void pause(){
System.out.println("dvd pause ...");
}
}
爆米花机
public class Popcorn {
//使用单例模式
private static Popcorn instance = new Popcorn();
public static Popcorn getInstance(){
return instance;
}
public void on(){
System.out.println("popcorn on ");
}
public void off(){
System.out.println("popcorn off");
}
public void pop(){
System.out.println("popcorn is popcorn");
}
}
屏幕
public class Screen {
//使用单例模式
private static Screen instance = new Screen();
public static Screen getInstance(){
return instance;
}
public void up(){
System.out.println("Screen up ");
}
public void down(){
System.out.println("Screen down");
}
}
影院灯光
public class TheaterLight {
//使用单例模式
private static TheaterLight instance = new TheaterLight();
public static TheaterLight getInstance(){
return instance;
}
public void on(){
System.out.println("TheaterLight on ");
}
public void off(){
System.out.println("TheaterLight off");
}
public void dim(){
System.out.println("TheaterLight dim .. ");
}
public void bright(){
System.out.println("TheaterLight bright ...");
}
}
外观类(用于整合)
public class HomeTheaterFacade {
//定义多个子系统对象
private TheaterLight theaterLight;
private Popcorn popcorn;
private Screen screen;
private DVDPlayer dvdPlayer;
//构造器
public HomeTheaterFacade() {
this.theaterLight = TheaterLight.getInstance();
popcorn = Popcorn.getInstance();
screen = Screen.getInstance();
dvdPlayer = DVDPlayer.getInstance();
}
//操作分4步
public void ready(){
popcorn.on();
popcorn.pop();
screen.down();
dvdPlayer.on();
theaterLight.on();
}
public void play(){
dvdPlayer.play();
}
public void pause(){
dvdPlayer.pause();
}
public void end(){
popcorn.off();
theaterLight.off();
screen.up();
dvdPlayer.off();
}
}