`
qingzi2534
  • 浏览: 254850 次
  • 性别: Icon_minigender_2
  • 来自: 烟台
社区版块
存档分类
最新评论

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

阅读更多

Spring使用配置文件管理所有的bean,该bean就是Spring工厂能产生的全部实例。下面是配置文件:

xml 代码
  1. <beans>  
  2.    <bean id="chinase" class="lee.Chinese"  />  
  3.    <bean id="american" class="lee.American" />  
  4. beans>  

<beans></beans>

 主程序部分如下:

java 代码
    1.   public class SpringTest    
    2.   
    3. {   public static void main(String[] args)    
    4.   
    5.     {   
    6.   
    7.         ApplicationContext ctx = new FileSystemXmlApplicationContext("bean.xml");   
    8.         Person  p= null;   
    9.         p=(person)ctx.getBean("chinese");   
    10.         System.out.println(p.sayHello("wawa"));   
    11.         System.out.println(p.sayCoogbye("wawa"));   
    12.         p=(Person)ctx.getBean("american");   
    13.         System.out.println(p.sayHello("wawa"));   
    14.        System.out.println(p.sayGoodBye("wawa"));   
    15.  }   
    16. }   
    17.   
    18.   
    19.     

使用Spring至少有一个好处:即使没有工厂类,程序一样可以使用工厂模式。

java 代码
  1. public class SpringTest    
  2. {   
  3.    public static void main(String[] args)   
  4.  {   
  5.    ApplicationContext ctx = new FileSystemXmlApplicationContext("bean.xml");   
  6.   Person p1 = null ;   
  7.   p1 = (Person)ctx.getBean("chinese");   
  8.   Person p2 = null ;   
  9.   p2 = (Person)ctx.getBean("chinese");   
  10.   System.out.println(p1==p2);   
  11.  }   
  12. }  

程序执行结果是: true

表明 Spring 对接收容器管理的全部bean,默认采用单态模式管理。性能上,单态的bean比非单态的bean更优秀。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics