首页 > 其他 > 详细

设计模式——外观模式

时间:2020-04-14 19:53:02      阅读:64      评论:0      收藏:0      [点我收藏+]

一、定义

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源码

 

设计模式——外观模式

原文:https://www.cnblogs.com/wqff-biubiu/p/12699661.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!