门面模式——Head First Design Patterns

来源:互联网 发布:阿里云cdn加速设置 编辑:程序博客网 时间:2024/06/09 21:03

定义:集成子系统的接口,对外提供一个统一的接口,以方便高层接口对其调用。

 

使用场景:当对外提供的接口比较多,使用者很难掌握时

 

类图:

代码样例:

package headfirst.facade.hometheater;public class HomeTheaterFacade {Amplifier amp;Tuner tuner;DvdPlayer dvd;CdPlayer cd;Projector projector;TheaterLights lights;Screen screen;PopcornPopper popper; public HomeTheaterFacade(Amplifier amp,  Tuner tuner,  DvdPlayer dvd,  CdPlayer cd,  Projector projector,  Screen screen, TheaterLights lights, PopcornPopper popper) { this.amp = amp;this.tuner = tuner;this.dvd = dvd;this.cd = cd;this.projector = projector;this.screen = screen;this.lights = lights;this.popper = popper;} public void watchMovie(String movie) {System.out.println("Get ready to watch a movie...");popper.on();popper.pop();lights.dim(10);screen.down();projector.on();projector.wideScreenMode();amp.on();amp.setDvd(dvd);amp.setSurroundSound();amp.setVolume(5);dvd.on();dvd.play(movie);}  public void endMovie() {System.out.println("Shutting movie theater down...");popper.off();lights.on();screen.up();projector.off();amp.off();dvd.stop();dvd.eject();dvd.off();}public void listenToCd(String cdTitle) {System.out.println("Get ready for an audiopile experence...");lights.on();amp.on();amp.setVolume(5);amp.setCd(cd);amp.setStereoSound();cd.on();cd.play(cdTitle);}public void endCd() {System.out.println("Shutting down CD...");amp.off();amp.setCd(cd);cd.eject();cd.off();}public void listenToRadio(double frequency) {System.out.println("Tuning in the airwaves...");tuner.on();tuner.setFrequency(frequency);amp.on();amp.setVolume(5);amp.setTuner(tuner);}public void endRadio() {System.out.println("Shutting down the tuner...");tuner.off();amp.off();}}


 

 

优点:1)简化对外接口,方便使用

缺点:

 

类似的设计模式: 1)装饰者模式,侧重于增强功能 2)命令模式,侧重于解耦请求和执行,并且支持可重复操作 3)门面模式,侧重于简化对外接口

 

配套的内功心法:1)最少知识原则,仅和关联性最强的对象打交道 2)不要调用其它方法返回的对象的方法,调用方法的原则:调用对象本身的方法;调用方法参数传递的对象的方法;方法内部创建或者实例化的对象的方法;组合到该对象的方法

0 0
原创粉丝点击