什么是外观模式?外观就说用起来好用的产品,譬如电视机,洗衣机,电脑 提高各种各样生活中所使用的工具。他们把里面 复杂的 处理都处理好,对外只提供了 开机、关机、操作等一些 按钮等。而我们开发中也常用到,譬如:你调用第三方的接口,第三方API 等,因为你也不知道对方的API 里面内部处理逻辑,你只知道对方API逻辑是如何处理的吗?其实你自己也不知道,因为别人封装好了,你只知道接口的含义。这就是外观模式
上类图
上代码:
public interface ElectricSwitchInter {
boolean on();
boolean off();
}
public class AirConditioner implements ElectricSwitchInter {
@Override
public boolean on() {
System.out.println("检测电压");
System.out.println("给外挂机通电...");
System.out.println("内部机器通电...");
System.out.println("测试各种器件能否提高正常使用");
System.out.println("空调启动成功....");
return true;
}
@Override
public boolean off() {
System.out.println("外机断电...");
System.out.println("等待内部机器检测...");
System.out.println("正式断电...");
return true;
}
}
public class TV implements ElectricSwitchInter {
@Override
public boolean on() {
System.out.println("检测电压");
System.out.println("通电显示器。。");
System.out.println("检查各种程序,并启动。。");
System.out.println("电视机启动成功,能播放。。");
System.out.println("电视机播放成功。。");
return true;
}
@Override
public boolean off() {
System.out.println("关闭电源...");
return true;
}
}
public class WashingMachine implements ElectricSwitchInter {
@Override
public boolean on() {
System.out.println("检测电压");
System.out.println("检测水压");
System.out.println("检测各种零件和电器是否能正常使用");
return true;
}
@Override
public boolean off() {
System.out.println("检测洗衣机内有水?");
System.out.println("正常断电....");
return true;
}
}
测试:
public class FacadeTest {
public static void main(String[] args) {
//使用已 封装好的 内容
ElectricSwitchInter tv = new TV();
tv.on();
ElectricSwitchInter airConditioner = new AirConditioner();
airConditioner.on();
ElectricSwitchInter washingMachine = new WashingMachine();
washingMachine.on();
tv.off();
airConditioner.off();
washingMachine.off();
}
}
输出结果:
检测电压
通电显示器。。
检查各种程序,并启动。。
电视机启动成功,能播放。。
电视机播放成功。。
检测电压
给外挂机通电...
内部机器通电...
测试各种器件能否提高正常使用
空调启动成功....
检测电压
检测水压
检测各种零件和电器是否能正常使用
关闭电源...
外机断电...
等待内部机器检测...
正式断电...
检测洗衣机内有水?
正常断电....