毛毛的小窝 — 关注技术交流、让我们一起成长

导航

单件模式(Singleton Pattern)


第一种:非线程安全
// Bad code! Do not use!
public sealed class Singleton
{
    
static Singleton instance=null;

    Singleton()
    {
    }

    
public static Singleton Instance
    {
        
get
        {
            
if (instance==null)
            {
                instance 
= new Singleton();
            }
            
return instance;
        }
    }
}
显然if(instance==null)对多线程很没有任何用处。

第二种:简单的线程安全型
public sealed class Singleton
{
    
static Singleton instance=null;
    
static readonly object padlock = new object();

    Singleton()
    {
    }

    
public static Singleton Instance
    {
        
get
        {
            
lock (padlock)
            {
                
if (instance==null)
                {
                    instance 
= new Singleton();
                }
                
return instance;
            }
        }
    }
}
关键在于【locking makes sure that all reads occur logically after the lock acquire, and unlocking makes sure that all writes occur logically before the lock release】

第三种:试图线程安全-利用双重检查
// Bad code! Do not use!
public sealed class Singleton
{
    
static Singleton instance=null;
    
static readonly object padlock = new object();

    Singleton()
    {
    }

    
public static Singleton Instance
    {
        
get
        {
            
if (instance==null)
            {
                
lock (padlock)
                {
                    
if (instance==null)
                    {
                        instance 
= new Singleton();
                    }
                }
            }
            
return instance;
        }
    }
}
不妥之处:【The Java memory model doesn't ensure that the constructor completes before the reference to the new object is assigned to instance】  【Without any memory barriers, it's broken in the ECMA CLI specification too】

第四种:不算太懒,但不用lock仍可以实现线程安全
public sealed class Singleton
{
    
static readonly Singleton instance=new Singleton();

    
// Explicit static constructor to tell C# compiler
    
// not to mark type as beforefieldinit
    static Singleton()
    {
    }

    Singleton()
    {
    }

    
public static Singleton Instance
    {
        
get
        {
            
return instance;
        }
    }
}
原因【static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced】

第五种:延迟初始化
public sealed class Singleton
{
    Singleton()
    {
    }

    
public static Singleton Instance
    {
        
get
        {
            
return Nested.instance;
        }
    }
    
    
class Nested
    {
        
// Explicit static constructor to tell C# compiler
        
// not to mark type as beforefieldinit
        static Nested()
        {
        }

        
internal static readonly Singleton instance = new Singleton();
    }
}

        在这五种方式中,2、4相对较好,5可以实现延时初始化,也不错。

posted on 2007-09-25 20:57  mjgforever  阅读(266)  评论(0编辑  收藏  举报