package com.atguigu.spring.beans.factory;

import java.util.HashMap;
import java.util.Map;

/**
 * 实例工厂方法:实例工厂的方法. 即先需要创建工厂本身,在调用工厂的实例方法来返回bean的实例 
 *
 */
public class InstanceCarFactory {
    private Map cars = null;

    public InstanceCarFactory() {
        cars = new HashMap();
        cars.put("audi", new Car("audi", 300000));
        cars.put("ford", new Car("ford", 400000));
    }

    public Car getCar(String brand) {
        return cars.get(brand);
    }

}
package com.atguigu.spring.beans.factory;

import java.util.HashMap;
import java.util.Map;

/**
 *  静态工厂方法:
 *      直接调用某一个类的静态方法就可以返回 bean 的实例(可以在不创建StaticCarFactory对象的方法下通过静态工厂方法就可以返回 bean 的实例)
 */
public class StaticCarFactory {
    private static Map cars = new HashMap();

    static{
        cars.put("audi", new Car("audi", 300000));
        cars.put("ford", new Car("ford", 400000));
    }

    //静态工厂方法
    public static Car getCar(String name) {
        return cars.get(name);
    }
}
package com.atguigu.spring.beans.factory;

public class Car {
    private String brand;
    private double price;

    public String getBrand() {
        return brand;
    }
    public void setBrand(String brand) {
        this.brand = brand;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Car [brand=" + brand + ", price=" + price + "]";
    }

    public Car() {
        System.out.println("容器被创建...");
        // TODO Auto-generated constructor stub
    }
    public Car(String brand, double price) {
        super();
        this.brand = brand;
        this.price = price;
    }

}
package com.atguigu.spring.beans.factory;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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);
    }

}