Spring 学习笔记(二)IOC之简单工厂模拟IOC

  • IOC不是一种技术,是一种思想。
  • 依赖注入是一种设计模式。
  • IOC不等于依赖注入。

是把实例化对象的操作交给IOC容器, 代码中用到对象的时候就去IOC容器中取。使得对象与对象之间松散耦合。

简单工厂模拟IOC

1. 创建People接口

package org.spring.example;

public interface People {
     public void getPeopleName();
}

2. 创建两个实现类 Kazhafei、Sadamu

package org.spring.example;

public class Kazhafei implements People {
    public Kazhafei( ) {   }

    @Override
    public void getPeopleName() {
        System.out.println("我是卡扎菲");
    }
}
package org.spring.example;

public class Sadamu implements  People{

    public Sadamu() {
        System.out.println("构造:萨达姆初始化");
    }

    @Override
    public void getPeopleName() {
        System.out.println("我是萨达姆");
    }
}

3. 新建配置文件 my.properties

people=org.spring.example.Sadamu

4. 新建工厂类

package org.spring.example;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PeopleFactory {

    private static Properties properties = new Properties();

    static {
        try {
            //读取配置文件并加载
            InputStream inputStream = PeopleFactory.class.getResourceAsStream("my.properties");
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    //从配置文件中获取到类的全名称,并通过反射实例化
    public static Object getBean(String name) {

        String className = properties.getProperty(name);
        try {
            return Class.forName(className).newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        throw new IllegalArgumentException("查无此人!");
    }
}

5. 在Test测试类中测试

package org.spring.example;


public class Test {
    public static void main(String[] args) {
        People people = (People) PeopleFactory.getBean("people");
        people.getPeopleName();
    }
}


输出: 

        构造:萨达姆初始化
        我是萨达姆
 

当需要获取Kazhafei对象时只需要修改配置文件(my.properties)中的类路径即可。

如果按照传统方式new对象出来的话,  就得改代码了。

猜你喜欢

转载自blog.csdn.net/baitianmingdebai/article/details/84994171