LGX.NET
漂泊...

单线程

public class Singleton
{
    
private static Singleton instance;
    
private Singleton() { }//私有实例构造器,如果自己不提供,编译器会自动生成共有无参构造器

    
public static Singleton Instance
    {
        
get
        {
            
if (instance == null)
            {
                instance 
= new Singleton();
            }
            
return instance;
        }
    }
}
多线程
class Multithread_singleton
{
    
private static volatile Multithread_singleton instance = null;//volatile保证代码不会被微调
    private static object lockHeper = new object();

    
private Multithread_singleton() { }

    
public static Multithread_singleton Instance
    {
        
get
        {
            
if (instance == null)
            {
                
lock (lockHeper)//double check 保证多线程不会同时进入
                {
                    
if (instance == null)
                    {
                        instance 
= new Multithread_singleton();
                    }
                }
            }
            
return instance;
        }
    }
    
}
posted on 2006-09-03 22:17  LGX.NET  阅读(112)  评论(0)    收藏  举报