工厂模式
接口
public interface MyInterface { void method(); Integer getType(); }
枚举类
1 public enum MyInterfaceType { 2 3 A(1, "MyClassA"), 4 5 B(2, "MyClassB"), 6 7 private Integer type; 8 9 private String desc; 10 11 MyInterfaceType(Integer type, String desc) { 12 this.type = type; 13 this.desc = desc; 14 } 15 16 public Integer getType() { 17 return type; 18 } 19 20 public void setType(Integer type) { 21 this.type = type; 22 } 23 24 public String getDesc() { 25 return desc; 26 } 27 28 public void setDesc(String desc) { 29 this.desc = desc; 30 } 31 }
实现接口的实体类
1 public class MyClassA implements MyInterface { 2 3 @Override 4 void method() { 5 //do something; 6 } 7 8 @Override 9 Integer getType() { 10 return MyInterfaceType.A.getType(); 11 } 12 }
1 public class MyClassB implements MyInterface { 2 3 @Override 4 void method() { 5 //do something; 6 } 7 8 @Override 9 Integer getType() { 10 return MyInterfaceType.B.getType(); 11 } 12 }
SpringLocator
1 public class SpringLocator implements ApplicationContextAware{ 2 3 private static ApplicationContext applicationContext; 4 5 @SuppressWarnings("unchecked") 6 public static <T> T getBean(String name) { 7 return (T) applicationContext.getBean(name); 8 } 9 10 @SuppressWarnings("unchecked") 11 public static <T> T getBean(Class<T> clazz) { 12 return (T) BeanFactoryUtils.beanOfType(applicationContext, clazz); 13 } 14 15 public void setApplicationContext(ApplicationContext applicationContext) throws BeansException{ 16 SpringLocator.applicationContext = applicationContext; 17 } 18 19 public static ApplicationContext getApplicationContext() { 20 return applicationContext; 21 } 22 23 public static TaskExecutor getDefaultTaskExecutor() { 24 return getBean(BeanNameSpace.DEFAULT_TASK_EXECUTOR); 25 } 26 27 }
工厂
1 public class MyFactory { 2 3 private Map<Integer, MyInterface> myInterfaceMap = new ConcurrentHashMap<Integer, MyInterface>(); 4 5 private AtomicBoolean isInit = new AtomicBoolean(false); 6 7 private MyFactory() { 8 9 } 10 11 public boolean isInit() { 12 return isInit.get(); 13 } 14 15 public void init() { 16 Map<String, MyInterface> myInterfaceBeanMap = SpringLocator.getApplicationContext().getBeansOfType(MyInterface.class); 17 if (MapUtils.isNotEmpty(myInterfaceBeanMap)) { 18 for (MyInterface myInterface : myInterfaceBeanMap.values()) { 19 myInterfaceMap.put(myInterface.getType(), myInterface); 20 } 21 } 22 isInit.compareAndSet(false, true); 23 } 24 25 private static class SingleHolder { 26 27 private static MyFactory myFactory = new MyFactory(); 28 29 private SingleHolder() {} 30 31 public static MyFactory getInstance() { 32 if (!myFactory.isInit()) { 33 myFactory.init(); 34 } 35 return myFactory; 36 } 37 } 38 39 private static MyFactory getInstance() { 40 return SingleHolder.getInstance(); 41 } 42 43 public static MyInterface getMyInterface(Integer type) { 44 MyInterface myInterface = getInstance().myInterfaceMap.get(type); 45 Validate.notNull(myInterface, "myInterface is null"); 46 return myInterface; 47 } 48 }