• 创建型-配置工厂


    实际工作中可能会遇到“配置工厂”这种做法,这中做法并不属于设计模式,大概实现思路将要创建的对象配置到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 "拿铁咖啡(意大利风味)";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    二:bean.properties

    American=com.example.design.AmericanCoffee
    Latte=com.example.design.LatteCoffee
    
    • 1
    • 2

    三: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);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    四:Main

    public static void main(String[] args) {
        Coffee coffee = CoffeeConfigFactory.createCoffee("Latte");
        System.out.println(coffee.getName());
    }
    
    • 1
    • 2
    • 3
    • 4

    五:与工厂方法设计模式的比较

    • 当新增一个对象时工厂方法模式需要新增一个对应的工厂类文件,而配置工厂这种做法只需要在配置文件新增配置即可,这种做法更简单。
    • 配置工厂是在项目启动的时候会创建出所有的对象永驻到内存中不会被回收,用内存来换取方便。
  • 相关阅读:
    一篇学会JavaIO流(输入输出流)
    如何制作gif图片?
    蓝桥集训(附加面试题)第七天
    AlphaFold2源码解析(3)--数据预处理
    偏差与方差
    MySQL-约束,子查询,常用函数
    云计算 - 2 - HDFS文件系统的基本操作
    深入浅出DataSourceAutoConfiguration
    Apache 的配置与应用
    redis---非关系型数据库(NoSql)
  • 原文地址:https://blog.csdn.net/vbirdbest/article/details/125435301