Spring笔记4 工厂方法

2016年1月29日

9:37

静态工厂方法:

Phone.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.firefly.spring.beans.factory;
 
public class Phone {
    private String name;
    private int price;
    public Phone(String name) {
        super();
        this.name = name;
    }
    public Phone(String name, int price) {
        super();
        this.name = name;
        this.price = price;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }
 
}

StaticPhoneFactory.java

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.firefly.spring.beans.factory;
 
import java.util.HashMap;
import java.util.Map;
 
public class StaticPhoneFactroy {
    private static Map<String,Phone> phone =new HashMap<String,Phone>();
 
    static{
        phone.put(“iphone”, new Phone(“iphone”,5000));
        phone.put(“xiaomi”, new Phone(“xiaomi”,2000));
 
    }
    public static Phone getPhone(String name){
        return phone.get(name);
    }
}

bean配置:

 

1
2
3
4
<bean id=”phone1” class=”com.firefly.spring.beans.factory.StaticPhoneFactroy”
    factory-method=”getPhone”>
        <constructor-arg  value=”iphone”></constructor-arg>
</bean>

    factory-method来指定工厂方法,constructor-arg来给工厂方法赋值。

    以上静态工厂方法工作流程:在一个静态工厂类中先静态的配置好实例,并用map封装起来,在真正用bean创建实例的时候是以名字为钥匙找到对应的实例,用以创建对象;

    还有对应的动态工厂方法,只是它不用static修饰,在调用的时候才配置实例,原理与静态工厂相似。

 

注解配置方法:~~

 

已使用 Microsoft OneNote 2016 创建。