1、问题描述
小明家的电源总开关控制了家里的三个设备:空调、台灯和电视机。每个设备都有独立的开关密码,分别用数字1、2和3表示。即输入1时,空调关闭,输入2时,台灯关闭,输入3时,电视机关闭,当输入为4时,表示要关闭所有设备。请你使用外观模式编写程序来描述电源总开关的操作。
输入示例
4
1
2
3
4
输出示例
Air Conditioner is turned off.
Desk Lamp is turned off.
Television is turned off.
All devices are off.
2、外观模式
举个例⼦,假设你正在编写的⼀个模块⽤来处理⽂件读取、解析、存储,我们可以将这个过程拆成三部分,然后创建⼀个外观类,将⽂件系统操作、数据解析和存储操作封装在外观类中,为客户端提供⼀个简化的接⼝,如果后续需要修改⽂件处理的流程或替换底层⼦系统,也只需在外观类中进⾏调整
作者认为和代理模式类似,只是目的不一样
3、代码
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int number=sc.nextInt();
AirConditioner ac=new AirConditioner();
TableLamp tl=new TableLamp();
TV tv=new TV();
Facade fc=new Facade(ac,tl,tv);
for(int i=0;i<number;i++){
int n=sc.nextInt();
fc.turnOff(n);
}
}
}
interface Furniture{
void turnOff();
}
class AirConditioner implements Furniture{
@Override
public void turnOff() {
System.out.println("Air Conditioner is turned off.");
}
}
class TableLamp implements Furniture{
@Override
public void turnOff() {
System.out.println("Desk Lamp is turned off.");
}
}
class TV implements Furniture{
@Override
public void turnOff() {
System.out.println("Television is turned off.");
}
}
class Facade{
private AirConditioner ac;
private TableLamp tl;
private TV tv;
public Facade(AirConditioner a,TableLamp t,TV tv){
this.ac=a;
this.tl=t;
this.tv=tv;
}
public void turnOff(int tag){
if(tag==1){
ac.turnOff();
}else if(tag==2){
tl.turnOff();
}else if(tag==3){
tv.turnOff();
}else {
System.out.println("All devices are off.");
}
}
}