您最好的方法是創建一個單一工廠,您可以根據服務名稱some.property.xyz
存儲的數據庫com.domain.BusinessFunction1
填充該工廠。工廠將使用反射來構建類,使用Class.forName("com.domain.BusinessFunction1");
然後您可以調用此類上的一個方法,該方法易於使用,以獲取屬性名稱和值的映射。就我個人而言,我會創建另一個工廠,併爲每個業務功能具有特定對象。如果您沒有數據庫,則可以將業務功能的名稱值存儲在XML或枚舉中。
這是使用Singleton和HashMap
的想法。我建議你從數據庫填充工廠,以提供更大的靈活性。
的通用基接口
public interface IBusinessFunction {
public void doFunction();
public void setParameters(Map<String,String> paramMap);
}
業務功能
public class BusinessFunction1 implements IBusinessFunction {
@Override
public void doFunction() {
System.out.println(String.format("Function from business class %s called.", this.getClass().getName()));
}
@Override
public void setParameters(Map<String, String> paramMap) {
}
}
public class BusinessFunction2 implements IBusinessFunction {
@Override
public void doFunction() {
System.out.println(String.format("Function from business class %s called.", this.getClass().getName()));
}
@Override
public void setParameters(Map<String, String> paramMap) {
}
}
BusinessFactory
public class BusinessFactory {
private static BusinessFactory instance = null;
private Map<String, Class<? extends IBusinessFunction>> businessFunctionMap = null;
protected BusinessFactory() {
// Populate this from a database,
// for the ease of your example i will use a HashMap
businessFunctionMap = new HashMap<String, Class<? extends IBusinessFunction>>();
businessFunctionMap.put("some.property.xyz", BusinessFunction1.class);
businessFunctionMap.put("some.property.abc", BusinessFunction2.class);
}
public static BusinessFactory getInstance() {
if (instance == null) {
instance = new BusinessFactory();
}
return instance;
}
public IBusinessFunction getBusinessFunction(String property) {
IBusinessFunction businessFunction = null;
Class clazz = businessFunctionMap.get(property);
try {
Constructor constructor = clazz.getConstructor();
businessFunction = (IBusinessFunction) constructor.newInstance();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return businessFunction;
}
}
測試類和工廠
public class Example {
public static void main(String[] args) {
Map<String,String> parameters = new HashMap<String, String>();
parameters.put("Param1","param 1 value");
parameters.put("Param2","param 2 value");
IBusinessFunction businessFunction = BusinessFactory.getInstance().getBusinessFunction("some.property.abc");
businessFunction.setParameters(parameters);
businessFunction.doFunction();
}
}
你最好的方法是創建一個單獨的工廠,你可以從一個數據庫'com.domain.BusinessFunction1'對存儲服務的名稱填充'some.property.xyz' ,工廠將通過使用'Class.forName(「com.domain.BusinessFunction1」)來使用反射來構造類;'然後你可以在這個類上調用一個方法,這個方法需要易於使用,以獲得屬性名和值的映射。個人ID創建另一個工廠,併爲每個業務功能具有特定的對象。如果您沒有數據庫,您可以將業務功能的名稱值存儲在xml或枚舉中 –