实际工作中可能会遇到“配置工厂”这种做法,这中做法并不属于设计模式,大概实现思路将要创建的对象配置到properties文件中,然后读取这个配置文件,使用反射创建对象存储在一个静态全局变量中,然后当客户端获取的时候从全局对象中取即可。
public abstract class Coffee {
public abstract String getName();
}
public class AmericanCoffee extends Coffee {
@Override
public String getName() {
return "美式咖啡(美式风味)";
}
}
public class LatteCoffee extends Coffee {
@Override
public String getName() {
return "拿铁咖啡(意大利风味)";
}
}
American=com.example.design.AmericanCoffee
Latte=com.example.design.LatteCoffee
public class CoffeeConfigFactory {
private static Map<String, Coffee> coffeeMap = new HashMap<>();
static {
InputStream inputStream = CoffeeConfigFactory.class.getClassLoader().getResourceAsStream("bean.properties");
Properties properties = new Properties();
try {
properties.load(inputStream);
for (Object key : properties.keySet()) {
String classFullName = (String) properties.get(key);
Coffee coffee = (Coffee)Class.forName(classFullName).newInstance();
coffeeMap.put((String) key, coffee);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static Coffee createCoffee(String name) {
return coffeeMap.get(name);
}
}
public static void main(String[] args) {
Coffee coffee = CoffeeConfigFactory.createCoffee("Latte");
System.out.println(coffee.getName());
}