Spring中常用的设计模式:工厂模式

工厂模式

Beanfactory是一个类工厂,但和传统的类工厂不同。传统的类工厂仅负责构造一个或几个类的实例;而BeanFactory是类的通用工厂,不仅提供了创建Bean的功能,还提供了Bean实例缓存、生命周期管理、Bean实例代理等服务,最重要的是还管理着Bean和Bean之间的依赖关系。在 Spring 中有许多的 IoC 容器的实现供用户选择和使用。

实例

SpringIoc和工厂模式(反射实现)

1. 先实现简单工厂


interface Fruit {
    public void eat();
}

class Apple implements Fruit {
    public void eat() {
        System.out.println("吃苹果。");
    }
}

class Orange implements Fruit {
    public void eat() {
        System.out.println("吃橘子");
    }
}

class Factory { // 工厂类
    public static Fruit getInstance(String className) {
        Fruit f = null;
        if (className.equals("apple")) {
            f = new Apple();
        }
        if (className.endsWith("orange")) {
            f = new Orange();
        }
        return f;
    }
}

public class FactoryDemo {
    public static void main(String args[]) {
        Fruit f = Factory.getInstance("apple");
        f.eat();
    }
}

问题:若增加新水果,如香蕉,则工厂类也要修改。

解决:java的反射机制。

2. 工厂类(修改)

class Factory { 
    public static Fruit getInstance(String className) {
        Fruit f = null;
        try {  
            f = (Fruit) Class.forName(className).newInstance();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return f;
    }
}

问题:创建实例时,需要提供完整的类名。

3. 增加配置文件

class PropertiesOperate{  
    private Properties pro=null;  
    private File file=new File("d:"+File.separator+"fruit.properties");  
      
    public PropertiesOperate(){  
        pro=new Properties();  
        if(file.exists()){  
            try {  
                pro.loadFromXML(new FileInputStream(file));  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }else{  
            this.save();  
        }  
    }  
    private void save(){  
        pro.setProperty("apple","org.Apple");  
        pro.setProperty("orange", "org.Orange");  
        try {  
            pro.storeToXML(new FileOutputStream(this.file),"Fruit");  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
    public Properties getProperties(){  
        return pro;  
    }  
}

4. 测试类

public class FactoryDemo3 {
    public static void main(String args[]) {
        Properties pro=new PropertiesOperate().getProperties();  
        Fruit f= Factory.getInstance(pro.getProperty("orange")); 
        f.eat();
    }
}

5. 总结

通过配置文件,可以控制程序的执行,现在看起来有点像Spring的IoC了。

该程序使用了工厂模式,把所有的类放在一个Factory里面,而为了动态的管理这些类(即使增加了新的Fruit类,这个工厂也不用变化),就用了java的反射机制。

猜你喜欢

转载自blog.csdn.net/sinat_34341162/article/details/84111205