门面模式
门面模式描述为:为子系统中的一组接口提供一个统一的简单的接口。从而隐藏复杂的子系统业务逻辑调用,其目的是为了提供一个简单且统一的访问,例如一些公用API,驱动程序等。
案例说明
空调的制冷–refrigeration
[refrigeration]
和制热–heating,代表两种工作模式,所有复杂的控制工作(温测,风扇转速,是否除湿,温度调节等)都在门面所调用的方法中执行。所有的复杂逻辑都被门面方法隐藏起来了,并通过这两个方法公开,客户端使用时,只关心工作模式,而不关心具体实现,即使扩展程序,也不会影响到客户端使用,客户端感兴趣的仅是所需的服务而已,该方法的实现与客户端进行了解耦。
编码示例(订单支付)
AccountService.java
package com.facade;
public class AccountService {
//get customer balance
public Double getBalance(Long accountID) {
return 1000.0;
}
//check if customer id is valid
public boolean CKey(Long accountID) {
return true;
}
}
OrdersService.java
package com.facade;
public class OrdersService {
public boolean checkOrderState(Long orderID) {
return true;
}
public Long getOrder(Long accountID){
return 123L;
}
}
PaymentService.java
package com.facade;
public class PaymentService {
public boolean pay(Long accountID,Long orderID){
return true;
}
}
PaymentSystemFacade.java
package com.facade;
public class PaymentSystemFacade {
AccountService accountService = new AccountService();
OrdersService orderService = new OrdersService();
PaymentService paymentService = new PaymentService();
public boolean payForSpecifiedOrder(Long accountID, Long orderID) {
boolean result = false;
if (accountService.CKey(accountID) && orderService.checkOrderState(orderID)) {
if (paymentService.pay(accountID, orderID))
result = true;
else
result = false;
}
return result;
}
}
客户端需要调用支付功能时,只需要调用
payForSpecifiedOrder()
方法即可;