例子:
一个家庭私人影院有 爆米花机、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(); } }