Spring 实现策略模式
Posted 咩咩文
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring 实现策略模式相关的知识,希望对你有一定的参考价值。
1.策略接口
package org.apel.bowen.controller;
import java.math.BigDecimal;
/**
* 计算价格的接口
* @author Bowin
*
*/
public interface Strategy
/**
* 计算价格
* @return
*/
public BigDecimal calculatePrice();
2.实现接口
package org.apel.bowen.controller;
import java.math.BigDecimal;
import org.springframework.stereotype.Service;
/**
* 普通用户
* @author Bowin
*
*/
@Service("generalMember")
public class GeneralMember implements Strategy
@Override
public BigDecimal calculatePrice()
return new BigDecimal("100");
package org.apel.bowen.controller;
import java.math.BigDecimal;
import org.springframework.stereotype.Service;
/**
* vip用户
* @author Bowin
*
*/
@Service("vipMember")
public class VipMember implements Strategy
@Override
public BigDecimal calculatePrice()
return new BigDecimal("80");
package org.apel.bowen.controller;
import java.math.BigDecimal;
import org.springframework.stereotype.Service;
/**
* 超级会员
* @author Bowin
*
*/
@Service("superMember")
public class SuperMember implements Strategy
@Override
public BigDecimal calculatePrice()
return new BigDecimal("1");
3.策略控制器
package org.apel.bowen.controller;
import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
/**
* 策略管理器
* @author Bowin
*
*/
@Component
public class StrategyContext
/**
*使用线程安全的ConcurrentHashMap存储所有实现Strategy接口的Bean
*key:beanName
*value:实现Strategy接口Bean
*/
private final Map<String, Strategy> strategyMap = new ConcurrentHashMap<>();
/**
* 注入所有实现了Strategy接口的Bean
* @param strategyMap
*/
@Autowired
public StrategyContext(Map<String, Strategy> strategyMap)
this.strategyMap.clear();
strategyMap.forEach((k, v)-> this.strategyMap.put(k, v));
/**
* 计算价格
* @param memberLevel 会员等级
* @return 价格
*/
public BigDecimal calculatePrice(String memberLevel)
if(!StringUtils.isEmpty(memberLevel))
return strategyMap.get(memberLevel).calculatePrice();
return null;
4.客户端调用
package org.apel.bowen.controller;
import java.math.BigDecimal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 前端控制器
* @author Bowin
*
*/
@Controller
@RequestMapping
public class HelloController
@Autowired
private StrategyContext strategyContext;
@RequestMapping("calculatePrice")
public @ResponseBody BigDecimal calculatePrice(String memberLevel)
return strategyContext.calculatePrice(memberLevel);
5.访问测试:
http://localhost:9999/calculatePrice?memberLevel=vipMember 返回 80
以上是关于Spring 实现策略模式的主要内容,如果未能解决你的问题,请参考以下文章