外观模式是什么?
外观模式提供了统一的接口,用来访问子系统中的一群接口,外观定义了一个高层接口,让子系统更容易使用。
外观模式解决什么问题?
现有Projector和Light:
class Projector {
public void ProjectorOn() {
System.out.println("开投影仪");
}
public void ProjectorOff() {
System.out.println("关投影仪");
}
}
class Light {
public void LightOn() {
System.out.println("开灯");
}
public void LightOff() {
System.out.println("关灯");
}
}
当要看电影时(关电影操作则相反):
Projector projector = new Projector();
projector.ProjectorOn();
Light light = new Light();
light.LightOff();
- problem1:用户需要同时和两个类交互,当操作变多时,交互所需的类也越多
外观模式实现
新建MovieFacade包装Projector和Light,提供统一的方法暴露:
public class MovieFacade {
Projector projector;
Light light;
public MovieFacade(Projector projector, Light light) {
this.projector = projector;
this.light = light;
}
public void WatchMovie() {
projector.ProjectorOn();
light.LightOff();
}
public void endMovie() {
projector.ProjectorOff();
light.LightOn();
}
}
当要看电影时:
MovieFacade mf=new MovieFacade(new Projector(),new Light());
mf.WatchMovie();