【设计模式】简单工厂模式之模拟公司发放节假日礼品

一.概念

工厂模式(Factory Pattern)是 Java 中最常用的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式;在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。

二.场景

马上就是端午节了,公司一般都会给员工准备端午节礼品,让你感受到公司无微不至的关怀,让大家更加兢兢业业的工作,从而把你安排的明明白白。

三类图及代码实现

1.类图
工厂模式类图
2.代码实现

2.1礼品发放接口

public interface Present {
    void send(String id);
}

2.2粽子茶叶蛋

@Slf4j
public class ZongZiTeaEggPresent implements Present {
    @Override
    public void send(String id) {
        log.info("发放粽子茶叶蛋id:{}", id);
    }
}

2.3 礼品兑换券,当然券也可以去兑换粽子茶叶蛋

@Slf4j
public class CouponPresent implements Present {

    @Override
    public void send(String id) {
        log.info("发放优惠券id:{}", id);
    }
}

2.4工厂方法,获取具体发送礼品的类,主要是封装对象的创建,工厂模式的核心

public class PresentFactory {

    public Present getPresent(String presentType) {
        if (presentType == null) {
            return null;
        }
        if (presentType.equalsIgnoreCase("coupon")) {
            return new CouponPresent();
        }
        if (presentType.equalsIgnoreCase("zongziteaegg")) {
            return new ZongZiTeaEggPresent();
        }
        return null;
    }

}

四.测试验证

1.测试类

public class TestMain {

    public static void main(String[] args) throws Exception {

        PresentFactory presentFactory = new PresentFactory();
        Present coupon = presentFactory.getPresent("coupon");
        if (coupon == null) {
            throw new Exception("不存在的礼品发放规则");
        }
        coupon.send("1");

        System.out.println();

        Present zongziteaegg = presentFactory.getPresent("zongziteaegg");
        if (zongziteaegg == null) {
            throw new Exception("不存在的礼品发放规则");
        }
        zongziteaegg.send("2");
    }
}

分别模拟发放兑换券和粽子茶叶蛋

2.测试结果

23:27:06.612 [main] INFO com.microsoft.designpatten.factory.CouponPresent - 发放优惠券id:1

23:27:06.620 [main] INFO com.microsoft.designpatten.factory.ZongZiTeaEggPresent - 发放粽子茶叶蛋id:2
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值