java设计模式---外观模式(facade pattern)

GoF提出的设计模式总共有23种,根据目的准则分类分为三大类:

创建型模式,共五种:单例模式、工厂方法模式、抽象工厂模式、建造者模式、原型模式。

结构型模式,共七种:适配器模式、装饰模式、代理模式、外观模式、桥接模式、组合模式、享元模式。

行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代器模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。
 

外观模式优点:

外观模式对外屏蔽了子系统的细节,因此外观模式降低了客户端对子系统使用的复杂性。

外观模式对客户端与子系统的耦合关系,让子系统内部的模块更容易维护和扩展。

通过合理的使用外观模式,可以更好地分层。因此当系统需要进行分层设计的时候,考虑使用facade模式

代码例子如下:

家庭中有多种电器,例子中我们存在电灯、爆米花机、dvd影碟机三样设备。我们做只能家居,希望一个遥控器可以控制多样电器,分别工作,那么就考虑到了外观模式。此处这个遥控器,即是我们在外观模式中提到的分层思想。

public class DVDPlayer {

    //采用单例 饿汉式
    private static DVDPlayer instance = new DVDPlayer();

    public static DVDPlayer getInstance(){
        return instance;
    }

    public void on(){
        System.out.println("DVD  开打");
    }

    public void off(){
        System.out.println("DVD 关闭");
    }

    public void play(){
        System.out.println("DVD  正在播放");
    }

    public void pause(){
        System.out.println("DVD  暂停");
    }
}

public class Latern {

    private static Latern instance = new Latern();

    public static Latern getInstance(){
        return instance;
    }

    public void on(){
        System.out.println("latern 打开了");
    }
    
    public void off(){
        System.out.println("latern 关闭了");
    }
}
public class PopCorn {

    private static PopCorn instance = new PopCorn();

    public static PopCorn getInstance(){
        return instance;
    }

    public void on(){
        System.out.println("popcorn 已经打开");
    }

    public void off(){
        System.out.println("popcorn 已经关闭");
    }

    public void already(){
        System.out.println("popcorn 已经完成");
    }
}

然后定义一个分层的类进行各子系统的调用:

public class HomeController {

    //定义各个电器的对象
    private DVDPlayer dvdPlayer;
    private Latern latern;
    private PopCorn popCorn;

    public HomeController(){
        this.dvdPlayer = DVDPlayer.getInstance();
        this.latern = Latern.getInstance();
        this.popCorn = PopCorn.getInstance();
    }

    //准备的动作
    public void ready(){
        popCorn.on();
        popCorn.already();
        latern.on();
        dvdPlayer.on();
    }

    //正在播放的
    public void doing(){
        dvdPlayer.play();
    }

    //暂停操作
    public void pause(){
        dvdPlayer.pause();
    }

    //结束操作
    public void over(){
        popCorn.off();
        latern.off();
        dvdPlayer.off();
    }

}

最后测试该功能:

public class Client {
    public static void main(String[] args) {
        //直接调用各个设备方法,很麻烦

        //所以我们转为调用HomeController去控制
        HomeController homeController = new HomeController();
        homeController.ready();
        homeController.doing();
        homeController.pause();
        homeController.over();
    }
}

输出结果:

popcorn 已经打开
popcorn 已经完成
latern 打开了
DVD  开打
DVD  正在播放
DVD  暂停
popcorn 已经关闭
latern 关闭了
DVD 关闭

Guess you like

Origin blog.csdn.net/LB_Captain/article/details/119968355