[设计模式笔记] 单例模式Singleton


单例模式 Singleton

单例模式(Singleton)是一种最简单的、适合入门的设计模式,它的目的是设计一种只能有一个实例的类,便于工程实践。

代码

Kotlin 实现

在Kotlin中,可以像动态语言那样不声明类而直接定义单例对象

object Singleton {
    var x = 5
    var y = "OK"
    fun show() {
        println("$x,$y")
    }
}

Singleton.show()

C++实现

在C++中,则要复杂一些,一种主流的方式是使用静态成员(static关键字)

#include 

using namespace std;

class Singleton {
public:
	static Singleton* instance;
	static Singleton* getInstance()	{
		if(instance == nullptr){
			instance = new Singleton();
		}
		return instance;
	}
	
public:
	int x = 5;
	string info = "OK";
	void show() {
		cout << x << "," << info << endl;
	}

//禁止拷贝和实例化
private:
	Singleton(const Singleton &rhs);
	Singleton();
	Singleton& operator=(const Singleton &rhs);
	
};
Singleton* Singleton::instance = NULL;
//在 C++ 中,static 非基本数据类型静态成员变量不能在类的内部初始化。

int main() 
{
	
	Singleton::getInstance()->show();
	
}

改进的单例模式

上面的实现代码是比较简单的设计模式,但在工程实践中,存在各种实际问题,如线程锁、内存泄漏等,可以参考这篇文章: C++ 单例模式 by Arkin

参考资料

  1. Design Patterns in Kotlin by dbacinski
  2. C++ 单例模式 by Arkin

废弃的部分

错误示范

你可能想到何不用匿名类并立即生成一个实例来做到单例:

class {
	public:
	int x = 5;
	string info = "Hello";
	void show() {
		cout << x << "," << info << endl;
	}
} singleton;

int main() 
{
	singleton.show();
}

这种方法很显然就会被攻破

auto anotherInstance = singleton;
cout << "anotherInstance: " << &anotherInstance << endl
	<< "singleton(originalInstance): " << &singleton << endl;

只需新建一个变量就能创建一个新实例。若我们加上禁止拷贝的代码,则不得不写出类名