设计模式——外观模式

一、定义

1、定义

外观模式又译为门面模式,

定义一个统一的外观接口,接口中封装了一系列操作,最少知道原则,降低了客户与一系列操作类之间的耦合。

 

2、UML类图

 

外观模式与适配器模式有相似的地方,但是外观模式注重的是一组接口的封装,而适配器模式注重的是接口之间的转换(适配)

外观模式一个重要的设计模式原则:最少知道原则,将客户端与具体的操作类解耦,仅保留客户端与外观接口的耦合。

3、简单实现

public class ThinkPad {
    public void on(){
        System.out.println("ThinkPad is on!");
    }

    public void off(){
        System.out.println("ThinkPad is off!");
    }
}

public class Light {
    public void on(){
        System.out.println("Light is on!");
    }

    public void off(){
        System.out.println("Light is off!");
    }
}

public class Website {
    public void open(){
        System.out.println("bilibili is open!");
    }

    public void close(){
        System.out.println("bilibili is close!");
    }
}

public interface ACGWatchFacade {
    void ACGWatch(String video);
    void ACGWatchFinish();
}

public class WatchMovieServiceImpl implements ACGWatchFacade {

    private ThinkPad thinkPad;
    private Light light;
    private Website website;

    public WatchMovieServiceImpl(){
        thinkPad = new ThinkPad();
        light = new Light();
        website = new Website();
    }


    @Override
    public void ACGWatch(String video){
        System.out.println("Get ready to watch a ACG video...");
        thinkPad.on();
        website.open();
        light.off();
    }

    @Override
    public void ACGWatchFinish(){
        System.out.println("Get ready to close a ACG video...");
        light.on();
        website.close();
        thinkPad.off();
    }
}

public class Client {
    public static void main(String[] args) {
        //客户端只知道facade
        ACGWatchFacade facade = new WatchMovieServiceImpl();
        facade.ACGWatch("LOL");
        facade.ACGWatchFinish();
    }
}

二、框架中的外观模式

暂时还没有发现,网上搜索tomcat源码中有用到,但是我还没有看tomcat源码

 

posted on 2020-04-14 17:58  FFStayF  阅读(303)  评论(0编辑  收藏  举报