Springboot中實現策略模式+工廠模式


  策略模式和工廠模式相信大家都比較熟悉,但是大家有沒有在springboot中實現策略和工廠模式?

  具體策略模式和工廠模式的UML我就不給出來了,使用這個這兩個模式主要是防止程序中出現大量的IF ELSE IF ELSE....。接下來咱們直接實現,項目結構圖:

  工廠類FactoryStrategy負責創建策略的工廠,代碼比較簡單,比較關鍵的一點是AutoWired一個Map<String, Strategy> 這個會在初始化的時候將所有的Strategy自動加載到Map中,是不是很方便。使用concurrentHashMap是防止多線程操作的時候出現問題。同時還要注意@Service注解。

package com.hqs.pattern.factory;

import com.hqs.pattern.strategy.Strategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author huangqingshi
 * @Date 2019-01-31
 */
@Service
public class FactoryForStrategy {

    @Autowired
    Map<String, Strategy> strategys = new ConcurrentHashMap<>(3);

    public Strategy getStrategy(String component) throws Exception{
        Strategy strategy = strategys.get(component);
        if(strategy == null) {
            throw new RuntimeException("no strategy defined");
        }
        return strategy;
    }

}

  接下來就是Strategy接口,就一個doOperation方法。

package com.hqs.pattern.strategy;

/**
 * @author huangqingshi
 * @Date 2019-01-31
 */
public interface Strategy {

    String doOperation();

}

  定義接口的實現,我定義了三個, 都類似,這里我就放出一個來吧。Component里邊的one是指定其名字,這個會作為key放到Map strategys里邊。

package com.hqs.pattern.strategy.impl;

import com.hqs.pattern.strategy.Strategy;
import org.springframework.stereotype.Component;

/**
 * @author huangqingshi
 * @Date 2019-01-31
 */
@Component("one")
public class StrategyOne implements Strategy {
    @Override
    public String doOperation() {
        return "one";
    }
}

  好了,寫一個Controller類,用於進行測試,當然我還是使用swagger,使用swagger的時候有個細節,就是注意生產上一定不能打開,否則是個非常可怕的事情。

package com.hqs.pattern.controller;

import com.hqs.pattern.factory.FactoryForStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author huangqingshi
 * @Date 2019-01-31
 */
@Controller
public class StrategyController {

    @Autowired
    FactoryForStrategy factoryForStrategy;

    @PostMapping("/strategy")
    @ResponseBody
    public String strategy(@RequestParam("key") String key) {
        String result;
        try {
            result = factoryForStrategy.getStrategy(key).doOperation();
        } catch (Exception e) {
            result = e.getMessage();
        }
        return result;
    }


}

  打開swagger進行測試,輸入one,返回one。輸入four,返回no strategy defined。后續如果有新策略的話,直接實現即可。

  好了,這塊就這么完成了,你get到了嗎?

  代碼地址:https://github.com/stonehqs/pattern.git

  歡迎拍磚~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM