`

Spring对单态与工厂模式的实现

阅读更多
这段时间研究了一下Spring对单态与工厂模式的实现,学习资料仍是李刚老师的《轻量级J2EE企业应用实战》。现在,我终于对“Spring中单态与工厂模式的实现”有了一个自认为还不错的认识,并能作出一些例子来了。下面贴出来与大家分享。

     Spring提供工厂模式的实现,Spring容器是最大的工厂,而且是个功能超强的工厂。Spring使用配置文件管理所有的bean,配置文件中bean由Spring工厂负责生成和管理。下面是关于两个实例的配置文件:
<!--  下面是xml文件的文件头-->
<?xml version="1.0" encoding="gb2312"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<!--  beans是Spring配置文件的根元素-->
<beans>
<!--  定义第一个bean,该bean的id为chinese->
<bean id="chinese" class="lee.Chinese"/>
<!--  定义第二个bean,该bean的id为american-->
     <bean id="american" class="lee.American"/>
</beans>

主程序部分如下:
public class SpringTest
{
     public static void main(String[] args)
     {
  //实例化Spring容器
         ApplicationContext ctx = new FileSystemXmlApplicationContext("bean.xml");
  //定义Person接口的实例
         Person p = null;
  //通过Spring上下文获得chinese实例
         p = (Person)ctx.getBean("chinese");
  //执行chinese实例的方法
         System.out.println(p.sayHello("wawa"));
         System.out.println(p.sayGoodBye("wawa"));
  //通过Spring上下文获得american实例
         p = (Person)ctx.getBean("american");
  //执行american实例的方法
         System.out.println(p.sayHello("wawa"));
         System.out.println(p.sayGoodBye("wawa"));
     }
}
使用Spring至少有一个好处:即使没有工厂类PersonFactory,程序一样可以使用工厂模式。所有工厂模式的功能,Spring完全可以提供。

下面对主程序部分做出简单的修改:
public class SpringTest
{
     public static void main(String[] args)
     {
  //实例化Spring容器
         ApplicationContext ctx = new FileSystemXmlApplicationContext("bean.xml");
  //定义Person接口的实例p1
         Person p1 = null;
  //通过Spring上下文获得chinese实例
         p1 = (Person)ctx.getBean("chinese");
  //定义Person接口的实例p1
  Person p2 = null;
p2 = (Person)ctx.getBean("chinese");
  System.out.println(p1 == p2);
     }
}

程序执行结果是:
true
表明:Spring对接受容器管理的全部bean,默认采用单态模式管理。除非必要,建议不要随便更改bean的行为方式:性能上,单态的bean比非单态的bean更优秀。
仔细检查上面的代码,发现如下特点:
1.除测试用主程序部分,代码并未出现Spring特定的类和接口。
2.调用者代码,也就是测试用主程序部分,仅仅面向Person接口编程。而无需知道实现类的具体名称。同时,可以通过修改配置文件来切换底层的具体实现类。
3.工厂无需多个实例,因此,工厂应该采用单态模式设计。Spring的上下文,也就是Spring工厂,已被设计成单态的。

Spring工厂模式,不仅提供了创建bean的功能,还提供对bean生命周期的管理。最重要的是:还可管理bean与bean之间的依赖关系。




本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/scott_gl/archive/2007/11/23/1899700.aspx
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics