JAVA设计模式笔记(外观模式)

外观模式:为子系统的一组接口提供了一致的界面,用来屏蔽内部子系统的细节,使得调用端只需跟接口发生调用,而无需关心内部细节。

外观模式的角色:
1)外观类:为调用端提供统一的调用接口,外观类知道哪些子系统负责处理请求,从而将调用端的请求代理给适当的子对象。
2)调用者:外观接口的调用者
3)子接口的集合:模块或者子系统,接受调用者指派的任务,功能的实际提供者

案例
家庭影院,有许多灯、电视、播放机等模块,需要编写程序实现家庭影院开启、播放、关闭的功能。
由于灯、电视、播放机自己也有开启、关闭的方法,因此不可能在客户端直接调用这些子模块的方法,最好是给客户端提供一个统一的调用接口去组合这些方法。

子模块

public class DVD {
    private static DVD instance=new DVD();
    public static DVD 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 play");
    }
}
public class TV {
    private static TV instance=new TV();
    public static TV getInstance(){
        return instance;
    }
    public void on(){
        System.out.println("TV on");
    }
    public void off(){
        System.out.println("TV off");
    }
}
public class Light {
    private static Light instance=new Light();
    public static Light getInstance(){
        return instance;
    }
    public void on(){
        System.out.println("light on");
    }
    public void off(){
        System.out.println("light off");
    }
}

外观类

public class Facade {
    private TV tv;
    private DVD dvd;
    private Light light;

    public Facade() {
        this.tv =TV.getInstance();
        this.dvd = DVD.getInstance();
        this.light = Light.getInstance();
    }

    public void on(){
        tv.on();
        light.on();
        dvd.on();
    }
    public void play(){
        dvd.play();
    }
    public void off(){
        light.off();
        dvd.off();
        tv.off();
    }
}

客户端调用

public class Client {
    public static void main(String[] args) {
        Facade facade=new Facade();
        facade.on();
        facade.play();
        facade.off();
    }
}
发布了56 篇原创文章 · 获赞 3 · 访问量 1629

猜你喜欢

转载自blog.csdn.net/qq_20786911/article/details/103542116