计算机系统应用教程网站

网站首页 > 技术文章 正文

C++ 设计模式之单例模式(含代码)

btikc 2024-09-24 08:07:33 技术文章 18 ℃ 0 评论

单例模式

概念:

单位模式是一种对象创建型模式,使用单位模式可以保证为一个位置生存唯一的实例对象。也就是说,在整个程序空间中,该位置存在一个实例对象

在应用系统开发中,我们常常有以下需求:

在多个线程之间,比如初始化一次socket资源,比如servlet环境,共享同一个资源,或者操作同一个对象

在整个程序空间使用全局变量,共享资源

大规模系统中为了性能的考虑,需要节省对象的创建时间等等

因为singletion模式可以保证为一个位置生成唯一的实例对象,所以这些情况singletion模式就派上用场了

实现单例的常用步骤

构造函数私有化

提供一个全局的静态方法

在类中定义一个静态指针,指向本类的变量的静态变量指针

单例-懒汉式

#include<iostream>
using namespace std;
class SingeLton
{
private:
	SingeLton()
	{
		cout << " SingeLton构造函数 " << endl;
	}

public:
	static SingeLton *getInstance()
	{
		if (m_psl == NULL)
		{
			m_psl = new SingeLton;
		}
		return m_psl;
	}
	static void FreeInstance()
	{
		if (m_psl != NULL)
		{
			delete m_psl;
			m_psl = NULL;
		}
	}
private:
	static SingeLton *m_psl;
};
SingeLton*SingeLton::m_psl = NULL;//对静态变量初始化的方法要放在类的外面
void main11()
{
	SingeLton*p1 = SingeLton::getInstance();
	SingeLton*p2 = SingeLton::getInstance();
	if (p1 == p2)
	{
		cout << "是同一个对象 " << endl;
	}
	else
	{
		cout << "不是同一个对象 " << endl;

	}
	SingeLton::FreeInstance();
	return;
	
}
void main()
{
	main11();
	cout << "hello.." << endl;
	system("pause");
	return;
}

单例_饿汉式

#include<iostream>
using namespace std;
class SingeLton
{
private:
	SingeLton()
	{
		cout << " SingeLton构造函数 " << endl;
	}

public:
	static SingeLton *getInstance()
	{
		
		return m_psl;
	}
	static void FreeInstance()
	{
		if (m_psl != NULL)
		{
			delete m_psl;
			m_psl = NULL;
		}
	}
private:
	static SingeLton *m_psl;
};
SingeLton*SingeLton::m_psl = new SingeLton;
void main11()
{
	SingeLton*p1 = SingeLton::getInstance();
	SingeLton*p2 = SingeLton::getInstance();
	if (p1 == p2)
	{
		cout << "是同一个对象 " << endl;
	}
	else
	{
		cout << "不是同一个对象 " << endl;

	}
	SingeLton::FreeInstance();
	return;
	
}
void main()
{
	main11();
	cout << "hello.." << endl;
	system("pause");
	return;
}

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表