设计模式 外观模式
概念
案例
代码实现
定义两个电器类 有共同的打开关闭接口
public class Light {
public void on(){
System.out.println("打开了灯---");
}
public void off(){
System.out.println("关闭了灯---");
}
}
public class TV {
public void on(){
System.out.println("打开了电视---");
}
public void off(){
System.out.println("关闭了电视---");
}
}
通过智能音响类来统一管理
public class SmartAppliancesFacade {
private Light light;
private TV tv;
public SmartAppliancesFacade() {
light = new Light();
tv = new TV();
}
public void say(String message){
if(message.contains("打开")){
this.on();
}
else if(message.contains("关闭")){
this.off();
}
else {
System.out.println("请重新说一遍");
}
}
private void on(){
light.on();
tv.on();
}
private void off(){
light.off();
tv.off();
}
}
测试使用:
public class Test {
public static void main(String[] args) {
SmartAppliancesFacade smartAppliancesFacade = new SmartAppliancesFacade();
smartAppliancesFacade.say("打开家电");
smartAppliancesFacade.say("关闭家电");
}
}