Relearn the factory model of design model in 30 days

Factory mode

The factory mode is also one of the most commonly used modes, which is a kind of creation mode. The parent class provides a method to create an object, allowing the subclass to determine the type of object to be instantiated.

The idea of ​​the factory pattern is to provide a structure for creating objects, let the subclass decide which factory to instantiate, and hide the specific implementation logic.

The most common thing in life is shopping. When we go to buy clothes, we can buy the corresponding brand (support Xinjiang cotton) when we go to different brand stores. We don't have to consider its realization process. There is also the fact that we participate in activities online, and we can choose different prizes after winning. The factory model can also be used here.

Multiple types of prizes are issued to realize the factory model

Assume that the product provides three interfaces

//优惠券接口
CouponResult sendCoupon(String uId, String couponNumber, String uuid);
//实物接口
Boolean deliverGoods(DeliverReq req);
//第三方兑换券接口
void grantToken(String phoneNumber, String cardId);

Define a common interface, and all commodities use this interface to ensure the unity of parameters.

public interface Commodity {
    
    
    /**
     * 
     * @param uid  用户id
     * @param commodityId 商品id
     * @param bizId  业务id
     * @param extData 其他信息
     */
   void sendCommodity(String uid, String commodityId, String bizId, Map<String,String> extData);

}

Implement coupon issuance interface

public class CouponCommodityService implements Commodity {
    
    

    private Logger logger = LoggerFactory.getLogger(CouponCommodityService.class);

    private CouponService couponService = new CouponService();

    public void sendCommodity(String uId, String commodityId, String bizId, Map<String, String> extData) throws Exception {
    
    
        CouponResult couponResult = couponService.sendCoupon(uId, commodityId, bizId);
        logger.info("请求参数[优惠券] => uId:{} commodityId:{} bizId:{} extData:{}", uId, commodityId, bizId, JSON.toJSON(extData));
        logger.info("测试结果[优惠券]:{}", JSON.toJSON(couponResult));
        if (!"0000".equals(couponResult.getCode())) throw new RuntimeException(couponResult.getInfo());
    }

}

Realize the physical distribution interface

public class GoodsCommodityService implements Commodity {
    
    

    private Logger logger = LoggerFactory.getLogger(GoodsCommodityService.class);

    private GoodsService goodsService = new GoodsService();

    public void sendCommodity(String uId, String commodityId, String bizId, Map<String, String> extData) throws Exception {
    
    
        DeliverReq deliverReq = new DeliverReq();
        deliverReq.setUserName(queryUserName(uId));
        deliverReq.setUserPhone(queryUserPhoneNumber(uId));
        deliverReq.setSku(commodityId);
        deliverReq.setOrderId(bizId);
        deliverReq.setConsigneeUserName(extData.get("consigneeUserName"));
        deliverReq.setConsigneeUserPhone(extData.get("consigneeUserPhone"));
        deliverReq.setConsigneeUserAddress(extData.get("consigneeUserAddress"));

        Boolean isSuccess = goodsService.deliverGoods(deliverReq);

        logger.info("请求参数[优惠券] => uId:{} commodityId:{} bizId:{} extData:{}", uId, commodityId, bizId, JSON.toJSON(extData));
        logger.info("测试结果[优惠券]:{}", isSuccess);

        if (!isSuccess) throw new RuntimeException("实物商品发放失败");
    }

    private String queryUserName(String uId) {
    
    
        return "李华";
    }

    private String queryUserPhoneNumber(String uId) {
    
    
        return "123456789";
    }

}

Implement third-party exchange interface

public class CardCommodityService implements Commodity {
    
    

    private Logger logger = LoggerFactory.getLogger(CardCommodityService.class);

    
    private IQiYiCardService iQiYiCardService = new IQiYiCardService();

    public void sendCommodity(String uId, String commodityId, String bizId, Map<String, String> extData) throws Exception {
    
    
        String mobile = queryUserMobile(uId);
        iQiYiCardService.grantToken(mobile, bizId);
        logger.info("请求参数[视频兑换卡] => uId:{} commodityId:{} bizId:{} extData:{}", uId, commodityId, bizId, JSON.toJSON(extData));
        logger.info("测试结果[视频兑换卡]:success");
    }

    private String queryUserMobile(String uId) {
    
    
        return "123456789";
    }

}

Create a factory (it looks a bit like a simple factory)

public class StoreFactory {
    
    

    public ICommodity getCommodityService(Integer commodityType) {
    
    
    	switch(commodityType){
    
    
    		case 1:return new CouponCommodityService();
    		break;
    		case 2:return new GoodsCommodityService();
    		break;
    		case 3:return new CardCommodityService();
    		break;
    		default:
    		throw new RuntimeException("不存在的商品服务类型");
    
    }

}

test

@Test
public void test_commodity() throws Exception {
    
    
    StoreFactory storeFactory = new StoreFactory();
   
    Commodity commodityService = storeFactory.getCommodityService(1);
    commodityService_1.sendCommodity("001", "EST43254264542", "47443272432888865", null);
   
}
模拟发放优惠券一张:001,EST43254264542,47443272432888865
请求参数[优惠券] => uId:001 commodityId:EST43254264542 bizId:47443272432888865 extData
测试结果[优惠券]{
    
    "code":"0000","info":"发放成功"}

Summary : The factory model avoids the logic coupling between the creator and the specific product and fulfills the responsibilities of a single. Each business logic implementation is completed in its own class, and the principle of opening and closing is met. There is no need to change the application and call method. You can introduce new product types in the program. But this will also bring some problems. If there are too many types of prizes, the sub-categories implemented will expand rapidly. Therefore, it is also necessary to use other modes for optimization, which will be gradually involved in subsequent design modes.

Guess you like

Origin blog.csdn.net/MAKEJAVAMAN/article/details/115281621