明天你会感谢今天奋力拼搏的你。
ヾ(o◕∀◕)ノヾ
public interface MyStrategy {
/**
* 做某些事情
* @return
*/
String doSomething();
}
接口实现:
@Component
public class HelloStrategy implements MyStrategy {
@Override
public String doSomething() {
return "Hello world";
}
}
Context上下文管理
@Component
public class ContextStrategy {
/**
* 获取具体策略实现
* @return
*/
public String getStrategy(String code) {
if (StringUtils.isEmpty(code)) {
return "code不能为空!.....";
}
//枚举里映射了code和spring bean的Id
String strategyBeanId = MyEnum.getId(code);//通过code拿到beanId
MyStrategy payStrategy = SpringUtils.getBean(strategyBeanId, MyStrategy.class);//通过beanId拿到bean对象
return payStrategy.doSomething();
}
}
枚举映射
public enum MyEnum {
/**
* Hello
*/
HELLO("hello","helloStrategy");
MyEnum(String key, String id) {
this.setKey(key);
this.setId(id);
}
public static String getId(String key){
for(MyEnum pay: MyEnum.values()){
if(StringUtils.equals(pay.getKey(),key)){
return pay.getId();
}
}
return "not find";
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
/**
* key
*/
private String key;
/**
* bean的id名字
*/
private String id;
}
全部评论