资讯详情

教程2,工厂方法实现发奖,抽象工厂实现redis集群,JDK动态代理应用

简单 工厂方法 抽象 区别

三个工厂的区别

  • 简单:工厂提供方法。不是设计模式,

    • 我要A对象 ,你给我A对象 ,B这里也要对象。你帮我选哪个?

    • 产品工厂——> 产品接口(if else)——> 产品A,B,C

  • 工厂方法:提供工厂方法。

    • 工厂里有提供不同对象的方法,你给我1,我给你优惠券服务,你可以直接用。

    • 抽象工厂——>产品接口——>工厂实现类(ABC工厂),A工厂 有产品A

    • 想用 哪个工厂调用那个产品?

  • 抽象:提供组合工厂的方法。 优化工厂方法。

    • JDKProxyFactory.getProxy(CacheService.class, EGMCacheAdapter.class);

      • 我告诉你用什么逻辑,用什么实现,我会为你创建代理对象
    • 抽象工厂-产品接口-工厂X——里面有产品A和B (同类产品,交给工厂)

      • 工厂C——有产品C
  • 一个窗口面、手擀面、油面 (给里面的人,服务员 帮我选)

  • 三个窗口:分开

  • 组合窗:清真(兰州拉面),普通(麻辣烫)

抽象工厂:

解释:围绕 超级工厂 创建其他工厂。

  • 该 超级工厂 又称为 其他工厂的工厂。

    • 这种设计模式 属于创建型 模式,
    • 它提供了一种 创建对象的最佳方式。
  • 球形工厂

  • 金字塔工厂

场景:替换Redis双集群升级,代理 抽象场景。

1. 工厂方法模式

1.1 基本定义

和 策略、适配器、模板方法 像

又称 工厂模式,

  • 是 一种 创建型 设计模式
  • 其 在 父类中 提供一个 创建对象的方法,
  • 允许 子类决定 实例化 对象的 类型

多种类型 不同接口的商品,统一奖励 构建服务场景

物流

  • 陆上
  • 海上

将商店定义为工厂 ===> 奖品接口

  • 兑换卡
  • 事物商品
  • 优惠券

1.2 基本的实体 和 实现

爱奇艺

public class IQiYiCard { 
         }  public class IQiYiCardService { 
              public void grantToken(String bindMobileNumber, String cardId) { 
                 System.out.println("一张爱奇艺会员卡模拟发放:"   bindMobileNumber   ","   cardId);     } } 

优惠券

//优惠券 public class CouponInfo { 
         } public class CouponResult { 
              private String code; // 编码     private String info; // 描述 }  public class CouponService { 
              public CouponResult sendCoupon(String uId, String couponNumber, String uuid) { 
        
        System.out.println("模拟发放优惠券一张:" + uId + "," + couponNumber + "," + uuid);
        return new CouponResult("0000", "发放成功");
    }

}

实物类

// 实物
public class GoodsInfo { 
        
}
public class DeliverReq { 
        

    private String userName;              // 用户姓名
    private String userPhone;             // 用户手机
    private String sku;                   // 商品SKU
    private String orderId;               // 订单ID
    private String consigneeUserName;     // 收货人姓名
    private String consigneeUserPhone;    // 收货人手机
    private String consigneeUserAddress;  // 收获人地址 
}
public class GoodsService { 
        

    public Boolean deliverGoods(DeliverReq req) { 
        
        System.out.println("模拟发货实物商品一个:" + JSON.toJSONString(req));
        return true;
    }
}

xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    
    <modelVersion>4.0.0</modelVersion>

    <groupId>cn.bugstack.design</groupId>
    <artifactId>tutorials-4.0-1</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>
        
        <!-- LOGGING begin -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.0.9</version>
            <exclusions>
                <exclusion>
                    <artifactId>slf4j-api</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        
        <dependency>
            <groupId>cn.bugstack.design</groupId>
            <artifactId>tutorials-4.0-0</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

发奖的请求 或 返回

public class AwardReq { 
        

    private String uId;                 // 用户唯一ID
    private Integer awardType;          // 奖品类型(可以用枚举定义);1优惠券、2实物商品、3第三方兑换卡(爱奇艺)
    private String awardNumber;         // 奖品编号;sku、couponNumber、cardId
    private String bizId;               // 业务ID,防重复
    private Map<String, String> extMap; // 扩展信息 
}

public class AwardRes { 
        

    private String code; // 编码
    private String info; // 描述
}

1.3 不使用设计模式

public class PrizeController { 
        

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

    public AwardRes awardToUser(AwardReq req) { 
        
        //返回的对象
        AwardRes awardRes = null;

        //请求对象转为json
        String reqJson = JSON.toJSONString(req);

        try { 
        

            logger.info("奖品发放开始{}。req:{}", req.getuId(), reqJson);

            // 按照不同类型方法商品[1优惠券、2实物商品、3第三方兑换卡(爱奇艺)]
            if (req.getAwardType() == 1) { 
        
                //优惠券service
                CouponService couponService = new CouponService();
                //调用具体的逻辑
                CouponResult couponResult = couponService.sendCoupon(req.getuId(), req.getAwardNumber(), req.getBizId());
                if ("0000".equals(couponResult.getCode())) { 
        
                    awardRes = new AwardRes("0000", "发放成功");
                } else { 
        
                    awardRes = new AwardRes("0001", couponResult.getInfo());
                }
            } else if (req.getAwardType() == 2) { 
        
                //实物的service
                GoodsService goodsService = new GoodsService();

                //创建 实物对象
                DeliverReq deliverReq = new DeliverReq();
                deliverReq.setUserName(queryUserName(req.getuId()));
                deliverReq.setUserPhone(queryUserPhoneNumber(req.getuId()));
                deliverReq.setSku(req.getAwardNumber());
                deliverReq.setOrderId(req.getBizId());
                deliverReq.setConsigneeUserName(req.getExtMap().get("consigneeUserName"));
                deliverReq.setConsigneeUserPhone(req.getExtMap().get("consigneeUserPhone"));
                deliverReq.setConsigneeUserAddress(req.getExtMap().get("consigneeUserAddress"));

                //发放
                Boolean isSuccess = goodsService.deliverGoods(deliverReq);
                if (isSuccess) { 
        
                    awardRes = new AwardRes("0000", "发放成功");
                } else { 
        
                    awardRes = new AwardRes("0001", "发放失败");
                }
            } else if (req.getAwardType() == 3) { 
        
                //获取 用户编号
                String bindMobileNumber = queryUserPhoneNumber(req.getuId());

                //创建 爱奇艺service
                IQiYiCardService iQiYiCardService = new IQiYiCardService();

                iQiYiCardService.grantToken(bindMobileNumber, req.getAwardNumber());

                awardRes = new AwardRes("0000", "发放成功");
            }
            logger.info("奖品发放完成{}。", req.getuId());
        } catch (Exception e) { 
        
            logger.error("奖品发放失败{}。req:{}", req.getuId(), reqJson, e);
            awardRes = new AwardRes("0001", e.getMessage());
        }

        return awardRes;
    }

    private String queryUserName(String uId) { 
        
        return "花花";
    }

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

}

1.4 使用设计模式

发放商品的接口

commodity 
英 /kəˈmɒdəti/  美 /kəˈmɑːdəti/  全球(美国)  
简明 牛津 新牛津  韦氏  柯林斯 例句  百科
n. 商品,货物;有用的东西,必需品
public interface ICommodity { 
        
	//用户ID ,奖品ID,业务ID,
    void sendCommodity(String uId, String commodityId, String bizId, Map<String, String> extMap) throws Exception;

}

爱奇艺卡实现

public class CardCommodityService implements ICommodity { 
        

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

    // 模拟注入
    private IQiYiCardService iQiYiCardService = new IQiYiCardService();

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

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

}

优惠券的实现

public class CouponCommodityService implements ICommodity { 
        

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

    private CouponService couponService = new CouponService();

    public void sendCommodity(String uId, String commodityId, String bizId, Map<String, String> extMap) throws Exception { 
        

        CouponResult couponResult = couponService.sendCoupon(uId, commodityId, bizId);

        logger.info("请求参数[优惠券] => uId:{} commodityId:{} bizId:{} extMap:{}", uId, commodityId, bizId, JSON.toJSON(extMap));
        logger.info("测试结果[优惠券]:{}", JSON.toJSON(couponResult));
        if (!"0000".equals(couponResult.getCode())) throw new RuntimeException(couponResult.getInfo());
    }

}

实物商品实现

public class GoodsCommodityService implements ICommodity { 
        

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

    private GoodsService goodsService = new GoodsService();

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

        Boolean isSuccess = goodsService.deliverGoods(deliverReq);

        logger.info("请求参数[实物商品] => uId:{} commodityId:{} bizId:{} extMap:{}", uId, commodityId, bizId, JSON.toJSON(extMap));
        logger.info("测试结果[实物商品]:{}", isSuccess);

         

标签: aqy212eh继电器aqy230sz继电器光耦继电器aqy211eha

锐单商城拥有海量元器件数据手册IC替代型号,打造 电子元器件IC百科大全!

锐单商城 - 一站式电子元器件采购平台