java 策略模式简单实现---spring

3 篇文章 0 订阅

策略模式

定义了算法族,分别封装起来,让它们之间可以相互替换,此模式让算法的变化独立于使用算法的客户。

我自己的理解就是通过接口实现不同的方法,同时又可以根据自己的选择自动选择使用哪个接口的实现。

情境:

       某客户需要订购多个资源,每一个资源在不同的资源池下面,不同的资源池下面的资源又是不同的。由于不想使用多个if else来判断用户选择的资源池来进行资源的选择,所以使用了策略模式来实现结构上的优化。

环境: 

基于SpringBoot实现的策略模式

DEMO:

        用户在application中自由的选择任何资源池进行订购时,由context上下文进行判断选择资源去资源池调用,从而实现结构上的优化。

Strategy接口:

 
  1. public interface Strategy {

  2.  
  3. String getVpcList(String id);

  4.  
  5. }

ResourceA实现:

 
  1. @Component("A")

  2. public class ResourceA implements Strategy {

  3.  
  4. @Override

  5. public String getVpcList(String id) {

  6. System.out.println("A,getVpcList ==========="+id);

  7. return id;

  8. }

  9. }

ResourceB实现:

 
  1. @Component("B")

  2. public class ResourceB implements Strategy {

  3.  
  4. @Override

  5. public String getVpcList(String id) {

  6. System.out.println("B strategy"+"====="+id);

  7. return id;

  8. }

  9.  
  10. }

SimpleContext实现:

       通过Spring将实现Strategy的实现类都自动注入到strategyMap类中,当用户传入选择的资源池时,自动根据资源池id去对应的资源池实现中查找资源。

 
  1. @Service

  2. public class SimpleContext {

  3.  
  4. @Autowired

  5. private final Map<String, Strategy> strategyMap = new ConcurrentHashMap<>();

  6.  
  7. public SimpleContext(Map<String, Strategy> strategyMap) {

  8. this.strategyMap.clear();

  9. strategyMap.forEach((k, v)-> this.strategyMap.put(k, v));

  10. }

  11.  
  12. public String getResource(String poolId){

  13. return strategyMap.get(poolId).getVpcList(poolId);

  14. }

  15.  
  16. }

Application实现:

 
  1. @RestController

  2. @RequestMapping("/test")

  3. public class TestController {

  4.  
  5. @Autowired

  6. private SimpleContext simpleContext;

  7.  
  8. @GetMapping("/choose")

  9. public String choose(@RequestParam String poolId){

  10. return simpleContext.getResource(poolId);

  11. }

  12.  
  13. }

   将SpringBoot工程跑起来,通过Postman进行测试。若是遇到404的情况或者500,请注意Application中进行注释包扫描路径:

 
  1. @SpringBootApplication

  2. @ComponentScan(basePackages = {"com.example.teststragy"})

  3. public class TeststragyApplication {

  4.  
  5. public static void main(String[] args) {

  6. SpringApplication.run(TeststragyApplication.class, args);

  7. }

  8. }

测试:

 

 

 通过这个简单的demo,就可以看到通过在Postman输入不同的资源池id,可以自动的拿到不同的资源。

通过实践总结下来,使用策略模式的好处就是通过一个封装的上下文可以自由的切换不同的算法,省去多重判断,同时可以具有很好的扩展性。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值