您的位置:首页 > 编程语言 > Java开发

23种java设计模式之外观模式

2016-07-31 16:03 495 查看
今天,我们就用一个家庭影院项目来说明外观模式。

家庭影院的项目分析:



在设计之前,我们可以分析一下,整个系统,我们需要做些什么呢?我们要打开爆米花机,放下屏幕,开投影仪,开音响,开DVD,选DVD,去拿爆米花,调暗灯光,播放电影,结束后关闭各种设备。这样整个系统会涉及很多对象,虽说不是每个对象都有联系,但是每个对象之间需统筹,比如投影仪和屏幕两个对象并没有什么联系,但是它们需要同时开启,所以我们利用外观者模式来解决这个项目,类图分析如下:



对于每一个对象,我们结合单例模式来做,因为这种系统每一个物理实体其实都是一个对象,不用new什么的来完成,他进来本身就是一个对象,物理实体直接单例就行了

接下来我给出某几个对象的代码,其他的就一样的,就不必一一给出了:

灯光类:TheaterLights

public class TheaterLights {

private static TheaterLights instance=null;

private TheaterLights(){

}

public static TheaterLights getInstance(){

if(instance==null){

instance=new TheaterLights();

}

return instance;

}

public void on(){

System.out.println("灯光打开!!!");

}

public void off(){

System.out.println("灯光关闭!!!");

}

public void dim(int d){

System.out.println("把亮度调为:"+d);

}

public void bright(){

dim(100);

System.out.println("灯光调亮");

}

}

音响类:Stereo

public class Stereo {

private static Stereo instance=null;

private static int volume=5;

private Stereo(){

}

public static Stereo getInstance(){

if(instance==null){

instance=new Stereo();

}

return instance;

}

public void on(){

System.out.println("音响打开!!!");

}

public void off(){

System.out.println("音响关闭!!!");

}

public void setVolume(int vol){

volume=vol;

System.out.println("音响调为:"+volume);

}

public void addVolume(){

if(volume<11){

volume++;

setVolume(volume);

}

}

}

.......

然后我们给出重点部分,外观模式,这里就相当于一个遥控器,它为了控制这个系统,它需要引用前面给出的那些对象,实例要获取到,然后用一个函数调用很多前面的方法,也就是用一个函数实现前面的一系列方法。

public class HomeTheaterFacade {

private TheaterLights light;

private Popcorn popcorn;

private Projector projector;

private Screen screen;

private DvdPlayer dvdPlayer;

private Stereo stereo;

public HomeTheaterFacade(){

light=TheaterLights.getInstance();

popcorn=Popcorn.getInstance();

projector=Projector.getInstance();

screen=Screen.getInstance();

dvdPlayer=DvdPlayer.getInstance();

stereo=Stereo.getInstance();

}

public void ready(){

popcorn.on();

popcorn.pop();

screen.down();

projector.on();

stereo.on();

dvdPlayer.on();

dvdPlayer.setCd();

light.dim(10);

}

public void end(){

popcorn.off();

light.bright();

screen.up();

projector.off();

dvdPlayer.setCd();

dvdPlayer.off();

}

public void play(){

dvdPlayer.play();

}

public void pause(){

dvdPlayer.pause();

}

}

最后测试Test:

public class Test {

public static void main(String[] args) {

HomeTheaterFacade homeTheaterFacade=new HomeTheaterFacade();

homeTheaterFacade.ready();

homeTheaterFacade.play();

}

}

总结:

外观模式:提供了一个统一的接口,来访问子系统中一群功能相关接口,也可以通俗点说成一个系统,你要做一个动作,会涉及到很多对象,可以把它放在同一个类里调用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息