设计模式---外观模式

定义:
又叫门面模式,提供了一个统一的接口,用于访问子系统中的一群接口
外观模式定义了一个高层接口,让子系统更容易使用
适用场景:
子系统越来越复杂,增加外观模式提供简单调用接口
构建多层系统结构,利用外观对象作为每层的入口,简化层间调用
优点:
简化了调用过程,无需了解深入子系统,防止带来风险
减少系统依赖、松散耦合
更好的划分访问层次
符合迪米特法则,即最少知道原则
缺点:
增加子系统、扩展子系统行为容易引入风险
不符合开闭原则
相关的设计模式
外观模式和中介模式
外观模式和单例模式
外观模式和抽象工厂模式

Coding
模拟积分兑换场景

public class PointsGift {

    private String name;

    public PointsGift(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
public class QualifyService {

    public boolean isAvailable(PointsGift pointsGift) {
        System.out.println("校验" + pointsGift.getName() + " 积分资格通过,库存通过");
        return true;
    }

}
public class PointsPaymentService {

    public boolean pay(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 GiftExchangeService {

    private PointsPaymentService pointsPaymentService = new PointsPaymentService();

    private ShippingService shippingService = new ShippingService();

    private QualifyService qualifyService = new QualifyService();

    public void giftExchange(PointsGift pointsGift){
        if (qualifyService.isAvailable(pointsGift)) {
            if (pointsPaymentService.pay(pointsGift)) {
                String shippingOrderNo = shippingService.shipGift(pointsGift);
                System.out.println("物流系统下单成功,订单号是:" + shippingOrderNo);
            }
        }
    }
}
public class Test {

    public static void main(String[] args) {
    	//符合迪米特法则,我关心礼物和兑换 至于下单、支付、物流 都无需关心
        PointsGift pointsGift = new PointsGift("T恤");
        GiftExchangeService giftExchangeService = new GiftExchangeService();
        giftExchangeService.giftExchange(pointsGift);
    }

}

Tomcat源码中大量使用了外观模式 搜索Facade结尾的类 都采用外观模式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值