外观模式也是门面模式。Facade Pattern
为系统中的一组接口提供一个一致的界面。
这个界面并不是传统意义上的前端界面。而是一个类,一个内部安排了很多其他类的类。通过它我们可以去调用这些类里面对外的接口,这些子系统可能都不知道有Facade这个门面类。
下面用一个小实例说明一下:
比如说,我们要点外卖,那么点外卖就有几个流程,比如:
‘
那么我们还需要一个商品类,这个类给我们提供商品信息,然后传递给需要商品属性的类。
话不多说,直接上代码:
Goods
package pxx;
public class Goods {
private String name;
public Goods(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
下面来看三个子系统
VerifyUserService
package pxx;
public class VerifyUserService {
public boolean verifyInfo() {
System.out.println("身份信息验证成功");
return true;
}
}
JudgePaymentService
package pxx;
public class JudgePaymentService {
public boolean JudgePayment(Goods goods) {
System.out.println(goods.getName() + "已经支付成功");
return true;
}
}
ShipService
package pxx;
public class ShipService {
//返回一个订单编号
public String deliveringGoods(Goods goods) {
System.out.println("商品" + goods.getName() + "开始配送");
return "12315";
}
}
FacadeService
package pxx;
public class FacadeService {
//门面类的作用
//导入前面三个系统
JudgePaymentService judgePaymentService = new JudgePaymentService();
ShipService shipService = new ShipService();
VerifyUserService verifyUserService = new VerifyUserService();
//做一个方法调用者几个接口完成动作
public void orderTakeOut(Goods goods) {
//然后开始模拟点餐操作
if(verifyUserService.verifyInfo()) {
if(judgePaymentService.JudgePayment(goods)) {
String goodsNum = shipService.deliveringGoods(goods);
System.out.println("订单号:" + goodsNum + goods.getName() + "已送出");
}
}
}
}
测试方法Test
package pxx;
public class Test {
public static void main(String[] args) {
Goods goods = new Goods("辣子鸡");
//只需要调用门面类就可以了
FacadeService facadeService = new FacadeService();
facadeService.orderTakeOut(goods);
}
}