C++单例模式

单例:一个类只能创建一个对象

实现步骤:

1.将构造函数声明为类的私有成员 private;

2.通过静态成员函数申请对象空间 ,并返回地址;

3.定义一个静态变量标记,记录对象的个数,该静态成员变量是开关变量,通过控制这个静态标记达到控制只创建一个对象的目的;

4.在析构函数中,将静态变量标记置成1,达到重复利用该静态变量标记目的;

源代码:

#include <iostream>

using namespace std;

// 单例模式,一个类只能创建一个对象
class CBase
{
	// 1.声明一个私有的类构造函数
private:
	CBase()
	{
		cout << "我是类的私有构造函数\n";
	}

public:
	// 2. 声明一个静态变量标记,用于控制类对象的创建
	static char flag;	// 类的静态成员函数必须在类外进行初始化
	
	// 3.声明一个共有的静态类指针成员函数,返回类的地址空间,
	// 目的:创建类对象可以通过类名作用域调用这个静态指针函数
	static CBase* function()
	{
		// 通过判断标记变量flag 进行函数的返回操作
		if (1 == flag)
		{
			// 将标记置成0,达到开关变量目的
			cout << "成功创建对象\n";
			flag = 0;
			// 返回类的地址空间
			return new CBase;
		}
		else
		{
			// 直接返回空
			cout << "已经有一个对象了,不能在进行创建新的对象了,请释放当前对象,已达到再一次创建对象目的\n";
			return NULL;
		}	
	}
	// 4.在析构函数中将静态变量标记flag置成1,达到重复利用目的
public:
	~CBase()
	{
		flag = 1;
	}

};
// 初始化类的静态成员变量
char CBase::flag = 1;	// 注意初始化的时候需要用类名作用域


int main(int argn, char* argv[])
{
	// 创建类的对象 (指针)
	const CBase* pt = CBase::function();	// 注意要用类名作用域调用类的静态指针成员函数
	
	// 尝试不释放类指针对象,进行创建对象
	const CBase* pt2 = CBase::function();

	system("pause");
	return 0;
}

程序运行结果1:

源代码2:

int main(int argn, char* argv[])
{
	// 创建类的对象 (指针)
	const CBase* pt = CBase::function();	// 注意要用类名作用域调用类的静态指针成员函数
	delete pt; // 释放

	// 尝试不释放类指针对象,进行创建对象
	const CBase* pt2 = CBase::function();
	delete pt2;

	system("pause");
	return 0;
}

程序运行结果2:

### 单例模式的基本概念 单例模式是创建型设计模式的一种,其核心思想是确保一个类仅有一个实例,并提供一个全局访问点来获取这个实例。在程序运行期间,单例模式可以保证一个类只有一个实例对象,并提供全局访问接口[^1][^2][^4]。 ### 实现方法 #### 饿汉式 饿汉式在程序开始时就创建实例,线程安全,但可能会造成资源浪费。 ```cpp #include <iostream> class Singleton { public: static Singleton& getInstance() { return instance; } void showMessage() { std::cout << "Hello from Singleton!" << std::endl; } private: Singleton() { std::cout << "Singleton Constructor Called" << std::endl; } // 防止复制 Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; static Singleton instance; }; Singleton Singleton::instance; int main() { Singleton& instance1 = Singleton::getInstance(); Singleton& instance2 = Singleton::getInstance(); instance1.showMessage(); if (&instance1 == &instance2) { std::cout << "Both instances are the same." << std::endl; } return 0; } ``` #### 懒汉式(非线程安全) 懒汉式在第一次使用时才创建实例,但非线程安全。 ```cpp #include <iostream> class Singleton { public: static Singleton* getInstance() { if (instance == nullptr) { instance = new Singleton(); } return instance; } void showMessage() { std::cout << "Hello from Singleton!" << std::endl; } private: Singleton() { std::cout << "Singleton Constructor Called" << std::endl; } // 防止复制 Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; static Singleton* instance; }; Singleton* Singleton::instance = nullptr; int main() { Singleton* instance1 = Singleton::getInstance(); Singleton* instance2 = Singleton::getInstance(); instance1->showMessage(); if (instance1 == instance2) { std::cout << "Both instances are the same." << std::endl; } return 0; } ``` #### 懒汉式(线程安全) 使用互斥锁保证线程安全,但会有一定的性能开销。 ```cpp #include <iostream> #include <mutex> class Singleton { public: static Singleton& getInstance() { std::lock_guard<std::mutex> lock(mutex); if (instance == nullptr) { instance = new Singleton(); } return *instance; } void showMessage() { std::cout << "Hello from Singleton!" << std::endl; } private: Singleton() { std::cout << "Singleton Constructor Called" << std::endl; } // 防止复制 Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; static Singleton* instance; static std::mutex mutex; }; Singleton* Singleton::instance = nullptr; std::mutex Singleton::mutex; int main() { Singleton& instance1 = Singleton::getInstance(); Singleton& instance2 = Singleton::getInstance(); instance1.showMessage(); if (&instance1 == &instance2) { std::cout << "Both instances are the same." << std::endl; } return 0; } ``` #### 基于局部静态变量(C++11及以上) 简洁、安全且高效,推荐使用。 ```cpp #include <iostream> class Singleton { public: static Singleton& getInstance() { static Singleton instance; return instance; } void showMessage() { std::cout << "Hello from Singleton!" << std::endl; } // 防止复制 Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; private: Singleton() { std::cout << "Singleton Constructor Called" << std::endl; } }; int main() { Singleton& instance1 = Singleton::getInstance(); Singleton& instance2 = Singleton::getInstance(); instance1.showMessage(); if (&instance1 == &instance2) { std::cout << "Both instances are the same." << std::endl; } return 0; } ``` ### 使用场景 - **资源管理**:例如数据库连接池、文件系统操作等,避免多个实例同时操作同一资源导致冲突。 - **配置信息**:如全局的配置文件管理,确保所有模块使用相同的配置信息。 - **日志记录**:保证所有日志信息都记录到同一个日志文件中。 ### 注意事项 - **线程安全**:在多线程环境下,需要确保单例的创建和访问是线程安全的,可采用互斥锁或局部静态变量的方式。 - **生命周期管理**:确保单例对象在整个程序生命周期内的正确性,避免内存泄漏。 - **可测试性**:单例模式可能会影响代码的可测试性,可考虑使用依赖注入等技术来提高可测试性。 - **避免滥用**:单例模式会引入全局状态,过度使用可能导致代码耦合度增加,难以维护和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值