定义
外观模式(Facade),也叫过程模式;外观模式为子系统中的一组接口提供一个一致的界面,此模式定义了 一个高层接口,这个接口使得这一子系统更加容易使用,而且也起到了屏蔽内部子系统的细节的作用,使得调用端只需跟这个接口发生交互,而无需关心这个子系统的内部细节。
外观模式的注意事项和细节
外观模式对外屏蔽了子系统的细节,因此外观模式降低了客户端对子系统使用的复杂性
外观模式对客户端与子系统的耦合关系 - 解耦,让子系统内部的模块更易维护和扩展
通过合理的使用外观模式,可以帮我们更好的划分访问的层次,当系统需要进行分层设计时,可以考虑使用Facade模式
不能过多的或者不合理的使用外观模式,使用外观模式好,还是直接调用模块好。要以让系统有层次,利于维 护为目的
实现
/**
* 外观模式
*/
public class Facade {
private DVDPlayer dvdPlayer;
private Projector projector;
private Speaker speaker;
private Light light;
public Facade() {
this.dvdPlayer = DVDPlayer.getInstance();
this.projector = Projector.getInstance();
this.speaker = Speaker.getInstance();
this.light = Light.getInstance();
}
public void ready(){
dvdPlayer.on();
projector.down();
projector.focus();
speaker.on();
light.off();
}
public void play(){
dvdPlayer.play();
}
public void pause(){
dvdPlayer.pause();
}
public void off(){
dvdPlayer.off();
projector.up();
speaker.off();
light.on();
}
}
class DVDPlayer {
private DVDPlayer() {
}
public void on() {
System.out.println("打开播放器");
}
public void play(){
System.out.println("开始播放");
}
public void pause() {
System.out.println("暂停播放器");
}
public void off() {
System.out.println("关闭播放器");
}
private static final DVDPlayer instance = new DVDPlayer();
public static DVDPlayer getInstance() {
return instance;
}
}
class Projector {
private Projector() {
}
public void up() {
System.out.println("上升投影");
}
public void down() {
System.out.println("下降投影");
}
public void focus() {
System.out.println("聚焦投影");
}
private static final Projector instance = new Projector();
public static Projector getInstance() {
return instance;
}
}
class Speaker {
private Speaker() {
}
public void on() {
System.out.println("打开音响");
}
public void off() {
System.out.println("关闭音响");
}
private static final Speaker instance = new Speaker();
public static Speaker getInstance() {
return instance;
}
}
class Light {
private Light() {
}
public void on() {
System.out.println("打开灯光");
}
public void off() {
System.out.println("关闭灯光");
}
private static final Light instance = new Light();
public static Light getInstance() {
return instance;
}
}
class TestFacade{
public static void main(String[] args) {
Facade facade = new Facade();
//流程可控
facade.ready();
facade.play();
facade.pause();
facade.off();
}
}