1 概念
1 定义
外观模式(Facade Pattern):又叫门面模式,引入一个外观角色来简化调用者与各个子系统之间的交互,向客户端提供了一个统一的接口,用来访问子系统中的一群接口。
类型: 结构型
2 适用场景
3 优缺点
优点:
- 给各个子系统提供统一的入口,无需深入了解子系统,调用者使用起来很简单
- 把各个子系统和调用者解耦,扩展性会更好
- 更好的划分访问层次。有些子方法是不需要暴露给外部的,有些是需要的。我们把需要暴露的方法,集成在外观类上
- 符合迪米特法则,即最小知道法则。客户端只需要和外观类进行交互,不需要和子系统进行交互
缺点:
如果设计不合理,增加新的子系统时可能需要修改外观类或调用者的源代码,违背了“开闭原则”
2 代码实现
场景:积分商城,根据已有积分购买商品。涉及到的子系统为:积分校验系统,支付系统,物流系统.
调用者不需要知道校验,支付,物流的情况,只需要知道要使用积分,兑换哪个商品即可,所以构建积分兑换类,使调用者直接使用
1 2 3 4 5 6 7 8 9 10 11
| public class PointsGift { private String name;
public PointsGift(String name) { this.name = name; }
public String getName() { return name; } }
|
1 2 3 4 5 6
| public class QualifyService { public boolean isAvailable(PointsGift pointsGift){ System.out.println("校验"+pointsGift.getName()+" 积分资格通过,库存通过"); return true; } }
|
1 2 3 4 5 6 7
| public class PointsPaymentService { public boolean pay(PointsGift pointsGift){ System.out.println("支付"+pointsGift.getName()+" 积分成功"); return true; } }
|
1 2 3 4 5 6 7 8
| public class ShippingService { public String shipGift(PointsGift pointsGift){ System.out.println(pointsGift.getName()+"进入物流系统"); String shippingOrderNo = "666"; return shippingOrderNo; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| 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); } } } }
|
1 2 3 4 5 6 7
| public class Test { public static void main(String[] args) { PointsGift pointsGift = new PointsGift("T恤"); GiftExchangeService giftExchangeService = new GiftExchangeService(); giftExchangeService.giftExchange(pointsGift); } }
|