首页 > 其他分享 >开发技术(一)—— SpringBoot使用策略模式

开发技术(一)—— SpringBoot使用策略模式

时间:2023-02-07 14:56:51浏览次数:43  
标签:DemoService 策略 模式 class String 开发技术 public SpringBoot

Spring实现策略模式

策略模式简介

引言:
当程序中使用太多的if/else/switch来处理不同类型的业务时,会变得极难维护,通过策略模式可以更容易的实现业务扩展和维护。

模式概述:
策略模式需要定义一个策略接口,不同的策略都去实现策略接口,在需要调用过程中通过持有该策略接口,然后根据不同的场景去使用不同的实现类。

策略模式的优点:

  • 消除繁琐的 if、else判断逻辑;
  • 代码结构良好,便于阅读;
  • 符合开闭原则,扩展性好、便于维护;

策略模式的缺点:

  • 策略如果很多的话,会造成策略类臃肿;
  • 其他人使用时必须了解所有的策略类及其用途;

spring实现策略模式

一、编写一个策略接口

public interface DemoService {
    String doTest();
}

二、编写策略实现类

@Service("test1")
public class Test1ServiceImpl implements DemoService {
    @Override
    public String doTest() {
        return "我是Test1";
    }
}
@Service("test2")
public class Test2ServiceImpl implements DemoService {
    @Override
    public String doTest() {
        return "我是Test2";
    }
}

三、构建策略工厂, 使Service自动注入

/**
 * 工厂类
 * 根据传入的component选择对应的策略实现类
 *  - 例如:传入test1  则调用bean为test1的实现类
 */
@Component
public class DemoStrategyFactory  {
    @Autowired
    Map<String, DemoService> DemoServices = new ConcurrentHashMap<>();

    public DemoService getDemoService(String component){
        DemoService demoService = DemoServices.get(component);
        if(demoService== null) {
            throw new RuntimeException("策略模式没找到对应实现类");
        }
        return demoService;
    }
}

四、编写测试方法

@SpringBootTest(classes = SpringbootApplication.class)
public class strategyTest {
    @Autowired
    private DemoStrategyFactory demoStrategyFactory;

    @Test
    public void test(){
        String result = DemoService demoService = demoStrategyFactory.getDemoService("test1").doTest();
        //输出结果为 “我是Test1”
        System.out.println(result);
    }
}

标签:DemoService,策略,模式,class,String,开发技术,public,SpringBoot
From: https://www.cnblogs.com/luoxiao1104/p/17098323.html

相关文章