外观模式

一. 定义

        外观模式提供了一个统一的接口,用来访问子系统中的一群接口。外观定义了一个高层接口,让子系统更容易使用。

二. 模式起源

三. 原则

3.1 原则1

         最少知识原则: 减少对象之间的交互,只和你的“密友”谈话。

四. UML图

五. 代码

5.1 爆米花机类

package model.facade;

/**
 * 爆米花类
 */
public class Popcorn {

    public void begin() {
        System.out.println("i am begin popcorn...");
    }

    public void end() {
        System.out.println("popcorn has been closed...");
    }

}

5.2 灯光类

package model.facade;

/**
 * 灯光类
 */
public class Light {

    public void dark() {
        System.out.println("the light has been darked...");
    }

    public void bright() {
        System.out.println("i am brighting the light...");
    }

}

5.3 屏幕类

package model.facade;

/**
 * 屏幕类
 */
public class Screen {

    public void down() {
        System.out.println("the screen has been down...");
    }

    public void up() {
        System.out.println("the screen has been up...");
    }

}

5.4 DVD类

package model.facade;

/**
 * DVD类
 */
public class Dvd {

    public void open() {
        System.out.println("the dvd has been open...");
    }

    public void close() {
        System.out.println("the dvd has been closed...");
    }

}

5.5 看电影外观类

package model.facade;

/**
 * 看电影外观类
 */
public class MovieFacade {

    // 外观类维护了相关操作所需要的类
    private Popcorn popcorn;
    private Light light;
    private Screen screen;
    private Dvd dvd;

    public MovieFacade(Popcorn popcorn, Light light, Screen screen, Dvd dvd) {
        this.popcorn = popcorn;
        this.light = light;
        this.screen = screen;
        this.dvd = dvd;
    }

    /**
     * 外观类对外提供的更简便的方法  实现了客户和具体子系统之间的解耦 调用起来更方便
     */
    public void watchMovie() {
        this.popcorn.begin();
        this.light.dark();
        this.screen.down();
        this.dvd.open();
    }

}

5.6 测试类

package model.facade;

/**
 * 测试类
 */
public class Main {

    public static void main(String[] args) {

        // 使用旧方式看电影
        Popcorn popcorn = new Popcorn();
        Light light = new Light();
        Screen screen = new Screen();
        Dvd dvd = new Dvd();

        popcorn.begin();
        light.dark();
        screen.down();
        dvd.open();

        // 使用外观模式看电影
        MovieFacade movieFacade = new MovieFacade(popcorn, light, screen, dvd);
        movieFacade.watchMovie();

    }

}

5.7 结果

i am begin popcorn...
the light has been darked...
the screen has been down...
the dvd has been open...
i am begin popcorn...
the light has been darked...
the screen has been down...
the dvd has been open...

六. 感悟

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页