public class Factory {
public static Product produce(String concreteProductType) {
switch (concreteProductType) {
case "A" :
return new ConcreteProductA();
break;
case "B" :
return new ConcreteProductB();
break;
default :
throw new Exception("没有对应的产品类型");
break;
}
}
}
public Class Factory {
public static Product produce(String concreteProductClassPathName) throw Exception {
try {
Product product = (Product)Class.forName(concreteProductClassPathName).newInstance();
return product;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
throw new Exception("没有对应的产品");
}
}
A=com.oxford.factory.simple.ConcreteProductA
B= com.oxford.factory.simple.ConcreteProductB
public Class PropertyReader {
public static Map<String, String> property = new HashMap<>();
public Map<String, String> readProperty(String fileName) {
Properties properties = new Properties();
InputStream input = getClass.getResourceAsStream(fileName);
try {
pro.load(input);
Iterator<String> iterator = pro.StringPropertyNames().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
String value = properties.getProperty(key);
map.put(key, value);
}
input.close();
} catch (IOException e) {
e.printStacTrace();
}
return map;
}
}
public Class Factory {
public static Product produce(String concreteProductType) throws Exception {
PropertyReader reader = new PropertyReder();
Map<String, String> property = reader.readProperty("property.properties");
try {
Product product = (Product)Class.forName(property.get(concreteProductType)).newInstance();
return product;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
throw new Exception("没有对应的产品");
}
}