// 灯的接口 interfaceLight{voidturnOn();voidturnOff();}// 真实的灯实现 classRealLightimplementsLight{@OverridepublicvoidturnOn(){System.out.println("Light is turned on.");}@OverridepublicvoidturnOff(){System.out.println("Light is turned off.");}}// 电视的接口 interfaceTV{voidturnOn();voidturnOff();voidchangeChannel(int channel);}// 真实的电视实现 classRealTVimplementsTV{@OverridepublicvoidturnOn(){System.out.println("TV is turned on.");}@OverridepublicvoidturnOff(){System.out.println("TV is turned off.");}@OverridepublicvoidchangeChannel(int channel){System.out.println("TV channel changed to: "+ channel);}}// 空调的接口 interfaceAirConditioner{voidturnOn();voidturnOff();voidsetTemperature(int temperature);}// 真实的空调实现 classRealAirConditionerimplementsAirConditioner{@OverridepublicvoidturnOn(){System.out.println("Air conditioner is turned on.");}@OverridepublicvoidturnOff(){System.out.println("Air conditioner is turned off.");}@OverridepublicvoidsetTemperature(int temperature){System.out.println("Air conditioner set to: "+ temperature +" degrees.");}}classSmartHomeFacade{privateLight light;privateTV tv;privateAirConditioner airConditioner;publicSmartHomeFacade(){
light =newRealLight();
tv =newRealTV();
airConditioner =newRealAirConditioner();}publicvoidturnOnLight(){
light.turnOn();}publicvoidturnOffLight(){
light.turnOff();}publicvoidturnOnTV(){
tv.turnOn();}publicvoidturnOffTV(){
tv.turnOff();}publicvoidchangeTVChannel(int channel){
tv.changeChannel(channel);}publicvoidturnOnAirConditioner(){
airConditioner.turnOn();}publicvoidturnOffAirConditioner(){
airConditioner.turnOff();}publicvoidsetAirConditionerTemperature(int temperature){
airConditioner.setTemperature(temperature);}}publicclassSmartHomeClient{publicstaticvoidmain(String[] args){SmartHomeFacade smartHomeFacade =newSmartHomeFacade();// 控制灯
smartHomeFacade.turnOnLight();// 做一些其他事情...
smartHomeFacade.turnOffLight();// 控制电视
smartHomeFacade.turnOnTV();
smartHomeFacade.changeTVChannel(5);// 做一些其他事情...
smartHomeFacade.turnOffTV();// 控制空调
smartHomeFacade.turnOnAirConditioner();
smartHomeFacade.setAirConditionerTemperature(24);// 做一些其他事情...
smartHomeFacade.turnOffAirConditioner();}}
将看到如下输出:
Light is turned on.
Light is turned off.TV is turned on.TV channel changed to:5TV is turned off.
Air conditioner is turned on.
Air conditioner set to:24degrees.
Air conditioner is turned off.