单例模式Singleton实现(C++&Java)

来源:互联网 发布:剑网三有挂机软件么 编辑:程序博客网 时间:2024/05/22 00:21

实现Singleton模式,分别用C++和Java实现。

首先C++:

class Singleton

{

private:

Singleton() {}

static Singleton* instance;

public:

static Singleton* getInstance()

{

if(instance == NULL)

{

instance = new Singleton();

}

return instance;

}

};

Singleton* Singleton::instance = NULL;

考虑到线程安全和异常安全,进行下面的扩展:

Class Lock

{

private:

CCriticalSection m_cs;

public:

Lock(CCriticalSection cs) : m_cs(cs)

{

m_cs.Lock();

}

~Lock()

{

m_cs.Unlock();

}

};

Class Singleton

{

private:

static Singleton* instance;

Singleton()

{

}

static CCriticalSection cs;


public:

static Singleton* getInstance()

{

if(instance == NULL)

{

Lock(cs);

if(instance == NULL)

instance = new Singleton();

}

return instance;

}

};

Singleton* Singleton::instance = NULL;


JAVA实现:

public class Singleton {

private static Singleton instance = null;

private Singleton() {}


public static Singleton getInstance() {

if(instance == null)   //1

instance = new Singleton();  //2

return instance;

}

}

不足:线程不安全,比如:

当线程1执行完1的时候,被挂起

线程2继续执行1,执行完1也被挂起

线程1恢复执行,创建出一个对象

线程2恢复执行,也创建出一个对象

所以会创建出两个实例。

改进:

public class Singleton {

private static Singleton instance = null;

private Singleton() {}

public static synchronized Singleton getInstance() {  //该函数被上锁,同一时刻只能被一个线程访问

if(instance == null) instance = new Singleton();

return instance;

}

}

不足:虽然是线程安全的,但是效率低下,一个时候只能被一个线程访问,不支持并发访问。

改进:

public class Singleton {

private static Singleton instance = null;

private Singleton() {}

public static Singleton getInstance() {

if(instance == null) {

synchronized(Singleton.class) {

if(instance == null)

instance = new Singleton();

}

}

return instance;

}

}

线程安全,而且效率较高,支持多线程并发访问。


0 0
原创粉丝点击