主要角色
- 外觀
職責
有點像裝飾器模式和適配器模式的意思。外觀模式的作用是對外提供一個新的接口,而業務邏輯則使用已有的代碼。
類圖
類關系示意圖
代碼
public class GiftExchangeService {
private QualifyService qualifyService = new QualifyService();
private PointsPaymentService pointsPaymentService = new PointsPaymentService();
private ShippingService shippingService = new ShippingService();
public void giftExchange(PointsGift pointsGift){
if(qualifyService.isAvailable(pointsGift)){
//資格校驗通過
if(pointsPaymentService.pay(pointsGift)){
//如果支付積分成功
String shippingOrderNo = shippingService.shipGift(pointsGift);
System.out.println("物流系統下單成功,訂單號是:"+shippingOrderNo);
}
}
}
}
---
public class PointsPaymentService {
public boolean pay(PointsGift pointsGift){
//扣減積分
System.out.println("支付"+pointsGift.getName()+" 積分成功");
return true;
}
}
---
public class QualifyService {
public boolean isAvailable(PointsGift pointsGift){
System.out.println("校驗"+pointsGift.getName()+" 積分資格通過,庫存通過");
return true;
}
}
---
public class ShippingService {
public String shipGift(PointsGift pointsGift){
//物流系統的對接邏輯
System.out.println(pointsGift.getName()+"進入物流系統");
String shippingOrderNo = "666";
return shippingOrderNo;
}
}
---
public class PointsGift {
private String name;
public PointsGift(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
使用
public class Test {
public static void main(String[] args) {
PointsGift pointsGift = new PointsGift("T恤");
GiftExchangeService giftExchangeService = new GiftExchangeService();
giftExchangeService.giftExchange(pointsGift);
}
}