设计模式-单例模式
作者:
也许
,
2022-05-22 20:48:39
,
所有人可见
,
阅读 199
设计模式基本原则
开放封闭原则
类的改动是通过增加代码进行的,而不是修改源代码。
依赖倒置原则
依赖于抽象(接口),不要依赖具体的实现(类),也就是针对接口编程。
单例模式
目的:保证为一个类只生成唯一的实例对象
应用场景:多个线程共享同一个资源或者操作同一个对象
实现单例模式步骤:
构造函数私有化
提供一个全局的静态方法(全局访问点)
在类中定义一个静态指针,指向本类的变量的静态变量指针
懒汉式单例模式
在全局的静态方法中创建对象
class Singelton
{
private:
Singelton()
{
m_singer = NULL;
m_count = 0;
cout << "构造函数Singelton ... do" << endl;
}
public:
static Singelton *getInstance()
{
if (m_singer == NULL )
{
m_singer = new Singelton;
}
return m_singer;
}
static void printT()
{
cout << "m_count: " << m_count << endl;
}
private:
static Singelton *m_singer;
static int m_count;
};
Singelton *Singelton::m_singer = NULL;
int Singelton::m_count = 0;
void main01_1()
{
cout << "演示 懒汉式" << endl;
Singelton *p1 = Singelton::getInstance();
Singelton *p2 = Singelton::getInstance();
if (p1 != p2)
{
cout << "不是同一个对象" << endl;
}
else
{
cout << "是同一个对象" << endl;
}
p1->printT();
p2->printT();
system("pause");
return ;
}
饿汉式单例模式
不在静态方法中创建对象,而是在全局区直接创建对象
class Singelton2
{
private:
Singelton2()
{
m_singer = NULL;
m_count = 0;
cout << "构造函数Singelton ... do" << endl;
}
public:
static Singelton2 *getInstance()
{
return m_singer;
}
static void Singelton2::FreeInstance()
{
if (m_singer != NULL)
{
delete m_singer;
m_singer = NULL;
m_count = 0;
}
}
static void printT()
{
cout << "m_count: " << m_count << endl;
}
private:
static Singelton2 *m_singer;
static int m_count;
};
Singelton2 *Singelton2::m_singer = new Singelton2;
int Singelton2::m_count = 0;
void main()
{
cout << "演示 饿汉式" << endl;
Singelton2 *p1 = Singelton2::getInstance();
Singelton2 *p2 = Singelton2::getInstance();
if (p1 != p2)
{
cout << "不是同一个对象" << endl;
}
else
{
cout << "是同一个对象" << endl;
}
p1->printT();
p2->printT();
Singelton2::FreeInstance();
Singelton2::FreeInstance();
system("pause");
}