大話設計模式之抽象工廠模式
阿新 • • 發佈:2018-12-18
抽象 工廠模式的本質:簡單工廠模式+反射,通過反射,將 簡單工廠模式中的switch case 去除,如果有新的演算法,
只需要 新增新的演算法類和配置檔案 即可
直接看程式碼把,之前學過 簡單工廠模式 就好理解了
/** * 基類 加 減 成 除 的共性 * */ public class OperationA { private Double numberA; private Double numberB; public Double getNumberA() { return numberA; } public void setNumberA(Double numberA) { this.numberA = numberA; } public Double getNumberB() { return numberB; } public void setNumberB(Double numberB) { this.numberB = numberB; } public double result(Double numberA,Double numberB){ double result=0; return result; } // abstract double result(Double numberA,Double numberB); }
public class Add extends OperationA{
public double result(Double numberA,Double numberB){
double result=0;
result=numberA+numberB;
System.out.println(result);
return result;
}
}
public class Div extends OperationA{ public double result(Double numberA,Double numberB){ double result=0; if (numberB!=0) { result=numberA/numberB; System.out.println(result); }else { System.out.println("除數不能為0"); } return result; } }
public class Sub extends OperationA{
public double result(Double numberA,Double numberB){
double result=0;
result=numberA-numberB;
System.out.println(result);
return result;
}
}
和簡單工廠模式不同之處
1.配置 檔案:jisuan.properties
add=shejimoshi.jiandangongchang.Add sub=shejimoshi.jiandangongchang.Sub div=shejimoshi.jiandangongchang.Div
2.讀取配置類
/**
* 二。讀取配置類
* */
public class ReaderProperties {
public Map<String, String> getPropertyAndKey() {
Map<String, String> map = new HashMap<String, String>();
Properties pt = new Properties();
try {
// 讀取對映檔案
InputStream in = getClass().getResourceAsStream("jisuan.properties");
// 從輸入流讀取屬性列表(鍵和元素對)
pt.load(in);
// 返回屬性列表所有鍵的列舉
Enumeration<?> en = pt.propertyNames();
// 逐行讀取列舉的key和value並存放在map中
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String value = pt.getProperty(key);
map.put(key, value);
System.out.println(map.get(key));
System.out.println(map.get(value));
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
}
3.工廠類
/**
* 三。計算工廠類
* */
public class JiSuanFactory {
public static OperationA getOperation(String key) {
// 獲取jisuan.properties檔案屬性列表
Map<String, String> propertyAndKey = new ReaderProperties().getPropertyAndKey();
// 通過對映找到對應得類
try {
OperationA newInstance = (OperationA) Class.forName(propertyAndKey.get(key)).newInstance();
return newInstance;
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
4.客戶端
/**
* 客戶端
* */
public class Test4 {
public static void main(String[] args) {
// 建立工廠
JiSuanFactory jiSuanFactory = new JiSuanFactory();
// 具體得操作
jiSuanFactory.getOperation("add").result(3.3, 3.3);
}
}