通过工厂方法创建bean实例

1.静态工厂方法

/**
* 静态工厂方法:直接调用某一个类的静态方法就可以返回bean实例

*
*/

1)先建立静态工厂
public class StaticCarFactory {
private static Map cars = new HashMap();
static {
cars.put("audi", new Car("audi",300000));
cars.put("baoma", new Car("baoma",500000));
}
//静态工厂方法
public static Car getCar(String name) {
return cars.get(name);
}
}2)配置文件





2.实例工厂方法

1)建立工厂

/**
* 实例工厂方法:实例工厂的方法 ,即现需要创建工厂本身,再调用工厂的实例方法来返回bean的实例
*
*
*/
public class InstanceCarFactory {
private Map cars = null;
public InstanceCarFactory() {
cars = new HashMap<>();
cars.put("audi", new Car("Audi",300000));
cars.put("bama", new Car("Baoma",500000));
}
public Car getCar(String brand) {
return cars.get(brand);
}
}

2)配置文件







3.main

public class Main {

public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-factory.xml");
Car car = (Car) ctx.getBean("car1");
System.out.println(car);
Car car2 = (Car) ctx.getBean("car2");
System.out.println(car2);
}

}

你可能感兴趣的:(通过工厂方法创建bean实例)