创建型-配置工厂
Posted vbirdbest
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了创建型-配置工厂相关的知识,希望对你有一定的参考价值。
实际工作中可能会遇到“配置工厂”这种做法,这中做法并不属于设计模式,大概实现思路将要创建的对象配置到properties文件中,然后读取这个配置文件,使用反射创建对象存储在一个静态全局变量中,然后当客户端获取的时候从全局对象中取即可。
一:entity
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 "拿铁咖啡(意大利风味)";
二:bean.properties
American=com.example.design.AmericanCoffee
Latte=com.example.design.LatteCoffee
三:ConfigFactory
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);
四:Main
public static void main(String[] args)
Coffee coffee = CoffeeConfigFactory.createCoffee("Latte");
System.out.println(coffee.getName());
五:与工厂方法设计模式的比较
- 当新增一个对象时工厂方法模式需要新增一个对应的工厂类文件,而配置工厂这种做法只需要在配置文件新增配置即可,这种做法更简单。
- 配置工厂是在项目启动的时候会创建出所有的对象永驻到内存中不会被回收,用内存来换取方便。
以上是关于创建型-配置工厂的主要内容,如果未能解决你的问题,请参考以下文章
Java设计模式之创建型:工厂模式详解(简单工厂+工厂方法+抽象工厂)