您的位置:首页 > 编程语言 > C语言/C++

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

2014-09-22 10:56 369 查看
实现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;

}

}

线程安全,而且效率较高,支持多线程并发访问。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: