effect
In ordinary development, we often encounter more than one interface implementation class, you need to select the appropriate circumstances to achieve class.
The easiest way is to write a selector for instance if-else to determine which implementation class, such as:
if(条件1){
return 实现类a的实例;
}else if(条件2){
retuen 实现类b的实例;
}
However, this method does not comply with the principle of opening and closing (the OCP), if implemented add a class, then the selector code is also a need to add else if.
So, after the reference to some colleagues and the code online, I put together a simple, consistent implementation of design principles.
A better choice is: Tools
This strategy uses the selected mode and utilizes Spring automatic injection characteristics.
First of all, we need to provide four tools:
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);
}
}
A better choice: Use Example
Suppose we have an interface shopping, Taobao and Jingdong two implementations.
So let inherit MatchingBean shopping interface code is as follows:
public interface BuyService extends MatchingBean<String> {
public String goShopping();
}
Then matching method implemented in the implementation class, as follows:
@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);
}
}
Finally, let's write a test class, look selector to use:
@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());
}
}
references
https://my.oschina.net/guanhe/blog/1821060