现在的位置: 首页 > 综合 > 正文

JAVA设计模式学习之----创建模式:单例模式

2013年10月17日 ⁄ 综合 ⁄ 共 587字 ⁄ 字号 评论关闭

Singleton模式主要作用是保证在Java应用程序中,一个类Class只有一个实例存在。
主要用于连接池的设计。。
如:形式一

  1. public
     
    class
     Singleton {
  2.     
  3.     
    private
     
    static
     Singleton st = 
    new
     Singleton();
  4.     
    private
     Singleton(){}
  5.     
  6.     
    public
     
    static
     Singleton getInstance(){
  7.         
    return
     st;
  8.     }
  9.     
  10.     
  11. }

形式二:lazy initialization

  1. public
     
    class
     Singleton {
  2.     
  3.     
    private
     
    static
     Singleton st = 
    null
    ;
  4.     
    private
     Singleton(){}
  5.     
  6.     
    public
     
    static
     synchronized Singleton getInstance(){
  7.         
    if
    (st == 
    null
    )
  8.             st =  
    new
     Singleton();
  9.         
  10.         
    return
     st;
  11.         
  12.     }
  13.     
  14.     
  15. }

注意第二种方法用了synchronized关键字,而且并不是每次都生成对象,使用时提高了生成实例的效率,但一般认为形式一更为安全些。

抱歉!评论已关闭.