1.Strategy接口
public interface Strategy {
String getVpcList(String id);
}
2.ResourceA实现
@Component("A")
public class ResourceA implements Strategy {
@Override
public String getVpcList(String id){
System.out.println("A,getVCPlist"+id);
return id;
}
}
3.ResourceB实现
@Component("B")
public class ResourceB implements Strategy {
@Override
public String getVpcList(String id){
System.out.println("B,getVCPlist"+id);
return id;
}
}
4.SimpleContext实现:
通过Spring将实现Strategy的实现类都自动注入到strategyMap类中,当用户传入选择的资源池时,自动根据资源池id去对应的资源池实现中查找资源。
@Service
public class SimpleContex {
@Autowired
private final Map<String,Strategy> strategyMap =new ConcurrentHashMap<>();
public SimpleContex(Map<String,Strategy> strategyMap){
this.strategyMap.clear();
strategyMap.forEach((k, v)-> this.strategyMap.put(k, v));
}
public String getResource(String poolid){
return strategyMap.get(poolid).getVpcList(poolid);
}
}
5.使用测试
@Autowired
private SimpleContex simpleContex;
@Test
public void strategytest(){
simpleContex.getResource("A") ; //执行A
simpleContex.getResource("B") ; //执行B
}
output:
image.png
网友评论