面试必问设计模式系列之工厂模式的详细解析

2021-08-23  本文已影响0人  攻城狮Chova

工厂模式

简单工厂模式

简单工厂类的实现方式

直接传入判断参数key

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("没有对应的产品");
    }
}

简单工厂模式总结

工厂方法模式

工厂方法模式总结

抽象工厂模式

抽象工厂模式总结

上一篇下一篇

猜你喜欢

热点阅读