C++ c# 分别实现单件模式

C#
1)

public sealed class Singleton
{
    
static Singleton instance = null;
    
private Singleton()
    
{
    }

    
public static Singleton Instance
    
{
        
get
        
{
            
if (instance == null)
            
{
                instance 
= new Singleton();
            }

            
return instance;
        }

    }

}

2) 线程安全

public sealed class Singleton
{
    
static Singleton instance = null;
    
static readonly object lockObj = new object();
    
private Singleton()
    
{
    }

    
public static Singleton Instance
    
{
        
get
        
{
            
lock (lockObj)
            
{
                
if (instance == null)
                
{
                    instance 
= new Singleton();
                }

            }

            
return instance;
        }

    }

}


C++:

1)
class Singleton
{
public:
   
static Singleton * Instance()
   
{
        
if0== _instance)
        
{
            _instance 
= new Singleton;
        }

        
return _instance;
   }


protected:
    Singleton()
{}
    
virtual ~Singleton(void){}
    
static Singleton* _instance;
}
;

2) 利用智能指针进行垃圾回收

class Singleton
{
    
public:
        
~Singleton(){}

    
static Singleton* Instance()
    
{
        
if(!pInstance.get())
        
{
        pInstance 
= std::auto_ptr<Singleton>(new Singleton());
        }

        
return pInstance.get();
    }

    
protected:  
        Singleton()
{}
    
private:
        
static std::auto_ptr<Singleton> pInstance;
 }
;

3) 线程安全

posted on 2008-04-21 16:49  清水无鱼  阅读(1173)  评论(1)    收藏  举报

导航