1. 前言:
不了解简单工厂模式请先移步: 在商城中使用简单工厂. 在这里主要是对 springboot 中使用简单工厂模式进行解析.
2. 问题:
什么是简单工厂: 它的实现方式是由一个工厂类根据传入的参数, 动态决定应该创建哪一个产品类 (这些产品类继承自一个父类或接口) 的实例.
然而在 Spring 中, 在启动容器对时候会通过 beanFactory 先创建初始化我们要用的类.
一个是要在使用的时候去创建一个产品类, 一个是预先已经加载好了我们要使用的对象, 那我们要如何解决这个问题呢?
3. 场景: 在一个商城系统中, 用户可以选择三种支付方式, 微信支付, 支付宝支付, 余额支付.
4: 方法:
我们只要将要用到的支付方式注入到容器中, 我们便可以根据 bean 到名字去容器中获取. 当然只要是很不灵活的.
其次, 我们只要再注入一个支付工厂, 每次去支付工厂拿自己想要的支付方式. 这样我们就可以像之前那样, 在自己想要的地方, 只需要注入一个支付工厂即可.
5. 实现:
步骤 1. 创建接口类
- public interface PaymentMethod {
- void pay();
- }
步骤 2. 实现接口类
- // 没有指定 value, 注入的 bean 默认首字母小写
- @Service
- public class Alipay implements PaymentMethod {
- @Override
- public void pay() {
- System.out.println("支付宝支付");
- }
- }
- @Service
- public class BalancePay implements PaymentMethod {
- @Override
- public void pay() {
- System.out.println("余额支付");
- }
- }
- @Service
- public class WechatPay implements PaymentMethod {
- @Override
- public void pay() {
- System.out.println("微信支付");
- }
- }
步骤 3. 直接在容器中, 根据 bean 的名字获取需要的对象.
- @SpringBootApplication
- public class SpringBootSimpleFactoryApplication {
- public static void main(String[] args) {
- ConfigurableApplicationContext context = SpringApplication.run(SpringBootSimpleFactoryApplication.class, args);
- // String[] beans = context.getBeanDefinitionNames();
- // for (String bean:beans) {
- // System.out.println("bean:"+bean);
- // }
- // 然而在实际开发中, 是不可能经常通过 context 获取 bean 的
- PaymentMethod paymentMethod = (PaymentMethod) context.getBean("alipay");
- paymentMethod.pay();
- }
步骤 4. 创建一个工厂, 根据所要给定的信息返回相应的 bean
- @Service
- public class PayFactory {
- @Autowired
- private Alipay alipay;
- @Autowired
- private BalancePay balancePay;
- @Autowired
- private WechatPay wechatPay;
- public PaymentMethod pay(String payType){
- switch (payType){
- case "balancePay":
- return balancePay;
- case "alipay":
- return alipay;
- case "wechatPay":
- return wechatPay;
- default:
- System.out.println("支付方式错误");
- }
- return null;
- }
- }
步骤 5. 在 controller 层调用支付工厂.(找不到 ResponseResult 类, 请移步单例模式之饿汉模式中获取)
- @RestController
- public class PayController {
- @Autowired
- private PayFactory payFactory;
- @RequestMapping("pay")
- public ResponseResult pay(String payType){
- ResponseResult responseResult = ResponseResult.getInstance();
- try {
- PaymentMethod paymentMethod = payFactory.pay(payType);
- paymentMethod.pay();
- responseResult.setMsg("操作成功");
- responseResult.setCode(0);
- }catch (Exception e){
- e.printStackTrace();
- responseResult.setMsg("支付类型错误");
- responseResult.setCode(1);
- }
- return responseResult;
- }
- }
源码:
在 springboot 中使用简单工厂模式
在工作中, 不能灵活的时候设计模式. 希望通过这次的学习, 可以加深对设计模式对理解.
接下来会继续整理出自己在工作对时候可以使用对设计模式, 不对望指点. 如果文章对您有帮助, GitHub 给个 start 吧.
来源: https://www.cnblogs.com/boychen/p/10624935.html