策略模式:
- 定义策略接口:
public interface CommStrategy {
String invoke();
}
- 策略实现类A:
import org.springframework.stereotype.Component;
@Component("A")
public class ACommStrategy implements CommStrategy {
@Override
public String invoke() {
return "ACommStrategy";
}
}
3.策略实现类B:
import org.springframework.stereotype.Component;
@Component("B")
public class BCommStrategy implements CommStrategy{
@Override
public String invoke() {
return "BCommStrategy";
}
}
4.执行不同策略:
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
@Service
public class ContentInvoker {
@Resource
private final Map map = new HashMap<>();
String getContent(String type) {
if (map.get(type) == null) {
return "unknown";
}
return map.get(type).invoke();
}
}
- 测试该策略模式:
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Slf4j
public class TestController {
@Autowired
private ContentInvoker ContentInvoker;
@RequestMapping(value = "open/test/{type}", method = RequestMethod.GET)
public String test(@PathVariable("type") String type) {
return ContentInvoker.getContent(type);
//return "AB";
}
}
- 结果是:请求类型type为A,那么输出ACommStrategy;请求类型为B,那么输出BCommStrategy。
主要原因是:spring注入的时候,在spring容器中,bean的name作为键,bean对象作为了value放在spring容器中。spring注入map的时候,也是这样的注入方式来处理。



