核心模块:外观角色,子系统角色

所有代码请访问:git@code.aliyun.com:289804201/PatternLearn.git

使用场景:有很多复杂的子系统,为客户提供一个简单的入口;
优点:客户并不需要各个子系统如何协同工作,减少客户和子系统的耦合;
缺点:不能很好的控制客户和子系统的交互;
注意:
1,与模版方法模式区别:模版方法模式里面内敛的是算法到父类,而不是外观模式中子类方法的集合

/**
 * Created by tory on 2018/1/4.
 * 外观模式,简而言之,就只将几个类聚合之,一步处理;
 * 核心模块:Facade外观角色,SubSystem子系统角色;
 * 与模版方法模式的区别:模版方法模式里面抽象模版类是算法的内敛到父类,而不是子类方法调用的集合
 */
public class FacadePattern {
    public static void main(String[] args) {
        //这里模仿智能家居
        Door door = new Door();
        Light light = new Light();
        BathRoom bath = new BathRoom();
        Television tv = new Television();
        SmartHomeFacade facade = new SmartHomeFacade(door, light, bath, tv);
        facade.comeHome();
        facade.watchTV();
        facade.sleep();
    }
}

//SubSystem 自动门子类
class Door {
    void open() {
        System.out.println("open the door...");
    }

    void close() {
        System.out.println("close the door...");
    }
}

//SubSystem 智能灯子类
class Light {
    void on() {
        System.out.println("light the room...");
    }

    void off() {
        System.out.println("dark the room...");
    }
}

//SubSystem 恒温水系统子类
class BathRoom {
    void on() {
        System.out.println("浴室开始烧热水...");
    }

    void off() {
        System.out.println("浴室停止烧热水...");
    }
}

//SubSystem 智能电视子类
class Television {
    void powerOn() {
        System.out.println("打开电视...");
    }

    void powerOff() {
        System.out.println("关闭电视...");
    }
}

//Facade 外观角色类
class SmartHomeFacade {
    //智能家居类,子类设置为private,对用户屏蔽细节
    private Door door;
    private Light light;
    private BathRoom bathRoom;
    private Television tv;

    SmartHomeFacade(Door door, Light light, BathRoom bath, Television tv) {
        this.door = door;
        this.light = light;
        this.bathRoom = bath;
        this.tv = tv;
    }

    void comeHome() {
        door.open();
        bathRoom.on();
    }

    void watchTV() {
        light.on();
        tv.powerOn();
    }

    void sleep() {
        door.close();
        bathRoom.off();
        tv.powerOff();
        light.off();
    }
}


内容打印
Hello World!
open the door...
浴室开始烧热水...
light the room...
打开电视...
close the door...
浴室停止烧热水...
关闭电视...
dark the room...

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐