简介
门面模式,又称外观模式,是结构型模式的一种。门面模式是为了解决项目中多个子系统的访问问题而设计的,它为多个子系统提供了一个统一的接口,这样使得子系统的调用更加容易。
代码示例
本次演示以获取不同水果颜色为例
不使用设计模式
定义获取水果演示的接口
public interface Fruit {
String getFruitColor();
}
苹果和香蕉类分别实现Fruit接口
public class Apple implements Fruit{
@Override
public String getFruitColor() {
return "red";
}
}
public class Banana implements Fruit{
@Override
public String getFruitColor() {
return "yellow";
}
}
客户端调用
public class Test {
public static void main(String[] args) {
Fruit apple = new Apple();
System.out.println(apple.getFruitColor());//red
Fruit banana = new Banana();
System.out.println(banana.getFruitColor());//red
}
}
使用门面模式
定义获取水果演示的接口
public interface Fruit {
String getFruitColor();
}
苹果和香蕉类分别实现Fruit接口
public class Apple implements Fruit{
@Override
public String getFruitColor() {
return "red";
}
}
public class Banana implements Fruit{
@Override
public String getFruitColor() {
return "yellow";
}
}
设置门面类
public class FruitColorFace {
private Apple apple;
private Banana banana;
public FruitColorFace() {
apple = new Apple();
banana = new Banana();
}
public String getAppleColor() {
return this.apple.getFruitColor();
}
public String getBananaColor() {
return this.banana.getFruitColor();
}
}
客户端调用
public class Test {
public static void main(String[] args) {
FruitColorFace face = new FruitColorFace();
System.out.println(face.getAppleColor()); //red
System.out.println(face.getBananaColor()); //yellow
}
}
总结
门面模式,就是在垂直调用下增加了一层接口,该接口起到了一个承上启下的作用,上面供上层调用,下面同一调用了底层,就相当于一个代理人。调用者不需要关心底层的其他系统,需要用时找门面即可完成,这样使得上层调用更容易。