作用
在日常開(kāi)發(fā)中式矫,我們常常會(huì)遇到一個(gè)接口有多個(gè)實(shí)現(xiàn)類時(shí),需要選擇合適的實(shí)現(xiàn)類的情況聪廉。
最簡(jiǎn)單的方法是寫(xiě)一個(gè)選擇器故慈,用if-else來(lái)判斷使用哪個(gè)實(shí)現(xiàn)類的實(shí)例,比如:
if(條件1){
return 實(shí)現(xiàn)類a的實(shí)例;
}else if(條件2){
retuen 實(shí)現(xiàn)類b的實(shí)例;
}
然而這種方法不符合開(kāi)閉原則(OCP)干签,如果再添加一個(gè)實(shí)現(xiàn)類拆撼,那么選擇器的代碼也需要再加一個(gè)else if。
所以竭贩,在參考了同事及網(wǎng)上的一些代碼后莺禁,我整理出了一種簡(jiǎn)潔的、符合設(shè)計(jì)原則的實(shí)現(xiàn)方式楼熄。
一種更好的選擇器:工具類
這種選擇器使用了策略模式柒傻,并且利用了Spring的自動(dòng)注入特性。
首先青柄,我們需要提供4個(gè)工具類:
public interface MatchingBean<K> {
boolean matching(K factor);
}
public interface MyFactoryList<E extends MatchingBean<K>, K> extends List<E> {
E getBean(K factor);
List<E> getBeanList(K factor);
}
public class MyFactoryArrayList<E extends MatchingBean<K>, K> extends ArrayList<E>
implements MyFactoryList<E, K>, Serializable {
@Override
public E getBean(K factor) {
Iterator<E> itr = iterator();
while (itr.hasNext()) {
E beanMatch = itr.next();
if (beanMatch.matching(factor)) {
return beanMatch;
}
}
return null;
}
@Override
public List<E> getBeanList(K factor) {
Iterator<E> itr = iterator();
while (itr.hasNext()) {
E beanMatch = itr.next();
if (!beanMatch.matching(factor)) {
itr.remove();
}
}
return this;
}
}
public class MyFactoryListEditor extends CustomCollectionEditor {
public MyFactoryListEditor() {
super(MyFactoryArrayList.class);
}
}
一種更好的選擇器:使用示例
假設(shè)我們有個(gè)購(gòu)物接口致开,有淘寶和京東兩個(gè)實(shí)現(xiàn)萎馅。
那么就讓購(gòu)物接口繼承MatchingBean,代碼如下:
public interface BuyService extends MatchingBean<String> {
public String goShopping();
}
然后在實(shí)現(xiàn)類里實(shí)現(xiàn)matching方法飒货,代碼如下:
@Service
public class JingdongService implements BuyService {
@Override
public String goShopping() {
return "Shopping in Jd";
}
@Override
public boolean matching(String factor) {
return "jd".equals(factor);
}
}
@Service
public class TaobaoService implements BuyService {
@Override
public String goShopping() {
return "Shopping in Taobao";
}
@Override
public boolean matching(String factor) {
return "taobao".equals(factor);
}
}
最后,咱們寫(xiě)個(gè)測(cè)試類晃虫,看下選擇器的使用方法:
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestMyBeanUtil {
@Autowired
MyFactoryList<BuyService,String> factoryList;
@Test
public void testOne(){
BuyService shop = factoryList.getBean("jd");
System.out.println(shop.goShopping());
}
}
參考文獻(xiàn)
https://my.oschina.net/guanhe/blog/1821060
系列文章總目錄:https://mp.weixin.qq.com/s/56JgXLArTAEDj1f3y4arLA