本设计模式资料源于慕课网,讲师:Geely 《Java设计模式精讲 Debug方式+内存分析》,本人作为自己手打整理作为学习的归纳总结。
一,模式介绍
1,定义和类型
-
定义:又叫门面模式,提供了一个统一的接口,用来访问子系统中的一群接口
-
外观模式定义了一个高层接口,让子系统更容易使用
-
类型:结构型
2,适用场景
- 子系统越来越复杂,增加外观模式提供简单接口调用
- 构建多层系统结构,利用外观对象作为每层的入口,简化层间调用
3,优点
1,简化了调用过程,无需深入了解子系统,防止带来风险。
2,减少系统依赖,松散耦合
3,更好的划分访问层次
4,符合迪米特原则,即最少知道原则
4,缺点
- 增加子系统,扩展子系统行为容易引入风险
- 不符合开闭原则
5,相关设计模式
- 外观模式与中介者模式
- 外观模式与单例模式
- 外观模式与抽象工厂模式
二,代码演示
1,业务场景
积分礼物需要兑换,兑换过程中涉及校验,支付,物流三个流程,需要做到一次调用。
2,代码
package com.try1.design.structural.facade;
public class PointGift {
private String name;
public PointGift(String name){
this.name=name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
package com.try1.design.structural.facade;
public class QualifyService {
public boolean isAvailable(PointGift pointGift){
//
System.out.println("积分校验成功,"+pointGift.getName()+"可以兑换");
return true;
}
}
package com.try1.design.structural.facade;
public class PointPaymentService {
public boolean pay(PointGift pointGift){
System.out.println("支付成功,"+pointGift.getName()+"兑换成功");
return true;
}
}
package com.try1.design.structural.facade;
public class ShippingService {
public String shipGift(PointGift pointGift){
System.out.println(pointGift.getName()+"加入物流系统");
String shippingOrderNO="666";
return shippingOrderNO;
}
}
package com.try1.design.structural.facade;
public class GiftExchangeService extends ChooseWay{
private QualifyService qualifyService=new QualifyService();
private PointPaymentService pointPaymentService=new PointPaymentService();
private ShippingService shippingService=new ShippingService();
@Override
public void GiftExchange(PointGift pointGift){
if (qualifyService.isAvailable(pointGift)){
if (pointPaymentService.pay(pointGift)){
shippingService.shipGift(pointGift);
}
}
}
}
package com.try1.design.structural.facade;
public abstract class ChooseWay {
public abstract void GiftExchange(PointGift pointGift);
}
package com.try1.design.structural.facade;
public class Test {
public static void main(String[] args) {
PointGift pointGift=new PointGift("奥特曼外套");
// GiftExchangeService giftExchangeService=new GiftExchangeService();
// giftExchangeService.GiftExchange(pointGift);
ChooseWay chooseWay=new GiftExchangeService();
chooseWay.GiftExchange(pointGift);
}
}
小结
外观设计模式有点类似与封装的概念,把原来很多很复杂的接口群,全部在一个接口中按顺序写好,外部只需要调用这一个类就能实现全部功能。
三,总结
这里其实还有一个在视频教程提到的小细节,例如最外层提取的chooway类,其实是一个便于之后进行流程选择的一个接口,方便之后的版本的替换。