实例工厂方法:将对象的创建过程封装到另外一个对象实例的方法里。
即实现需要创建工厂本身,再调用工厂的实例方法来返回bean的实例。
一、知识点
概念:
- factory-bean:指向实例工厂方法的bean。
- factory-method:指向实例工厂方法的名字。
- constructor-arg:如果工厂方法需要传入参数,则使用constructor-arg的value属性来配置参数。
实例工厂方法:将对象的创建过程封装到另外一个对象实例的方法里。
当客户端需要请求对象时,只需要简单的调用该实例方法,不需要关心对象的创建细节。
具体使用:
- 要声明通过实例工厂方法创建的bean。
- 在bean的factory-bean属性里指定拥有该工厂方法的bean。
- 在factory-method属性里指定该工厂方法的名称。
- 使用construtor-arg元素为工厂方法传递方法参数。
二、代码实现
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 29 30 31 32 33 34 35 |
package factory; public class god { private String to; private String be; public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getBe() { return be; } public void setBe(String be) { this.be = be; } @Override public String toString() { return "god [to=" + to + ", be=" + be + "]"; } public god(String to, String be) { super(); this.to = to; this.be = be; } } |
因为是实例工厂方法,所以必须创建实例。实例为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package factory; import java.util.HashMap; import java.util.Map; public class instancefactory { private Map<String, god> gods = null; public instancefactory() { gods = new HashMap<String, god>(); gods.put("xie", new god("xie", "isgod")); gods.put("godlikexie", new god("tobe", "happy")); } public god getgod(String name) { return gods.get(name); } } |
配置staticfactory.xml:
1 2 3 4 5 6 7 |
<!-- 配置工厂实例 --> <bean id="godfactory" class="factory.instancefactory"></bean> <!-- 通过工厂方法来配置bean --> <bean id="god2" factory-bean="godfactory" factory-method="getgod"> <constructor-arg value="xie"></constructor-arg> </bean> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package factory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class main { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("staticfactory.xml"); god god2 = (god) applicationContext.getBean("god2"); System.out.println(god2); } } |
运行结果为:
1 |
god [to=xie, be=isgod] |
正常输出了结果。
三、总结
再次总结一下配置参数:
- factory-bean:指向实例工厂方法的bean。
- factory-method:指向实例工厂方法的名字。
- constructor-arg:如果工厂方法需要传入参数,则使用constructor-arg的value属性来配置参数。
其实和静态工厂是非常类似的,应该很好理解。