C++常用设计模式之单例模式


前言

单例模式 (Singleton)
名称:Singleton(单件模式);
目的:保证一个类仅有一个实例,并提供一个访问它的全局访问点;

适用环境:

当类只能有一个实例而且客户可以从一个众所周知的访问点访问它时;
当这个唯一实例应该是通过子类化可扩展的,并且客户应该无需更改代码就能使用一个扩展的实例时。

一、单例模式是什么样的?

示例:单例模式(Singleton)也叫单态模式,是设计模式中最为简单的一种模式,甚至有些模式大师都不称其为模式,称其为一种实现技巧,因为设计模式讲究对象之间的关系的抽象,而单例模式只有自己一个对象,也因此有些设计大师并把把其称为设计模式之一。

二、使用场景

代码如下(示例):
返回对象,(不用关心最后释放)

#pragma once

class SingleTon_com
{
    
    
public:
    static SingleTon_com &GetInstance()
    {
    
    
        static SingleTon_com ins;
        return ins;
    }
	SingleTon_com(const SingleTon_com &) = delete;
	SingleTon_com &operator=(const SingleTon_com &) = delete;
    virtual ~SingleTon_com() {
    
    }

	void test()
	{
    
    
		printf("hello world!");
	}

protected:
	SingleTon_com() {
    
    }
};

template <class T>
class SingleTon
{
    
    
public:
    static T &GetInstance()
    {
    
    
        static T ins;
        return ins;
    }

    virtual ~SingleTon() {
    
    }
    SingleTon(const SingleTon &) = delete;
    SingleTon &operator=(const SingleTon &) = delete;

	void test()
	{
    
    
		printf("hello world!");
	}
protected:
    SingleTon() {
    
    }

};

返回指针的

#pragma once
class CP2PMgr
{
    
    
private:
	CP2PMgr(bool isCaller = true)
	{
    
    

	}

	CP2PMgr(const CP2PMgr &) = delete;
	CP2PMgr & operator = (const CP2PMgr &) = delete;

public:
	~CP2PMgr(void)
	{
    
    

	}
	static  CP2PMgr* getInstance()
	{
    
    
		if (p2pMgr == nullptr)
		{
    
    
			p2pMgr = new CP2PMgr(false);
		}
		return p2pMgr;
	}
private:
	//内部类,用来最后释放 p2pMgr
	class GC
	{
    
    
	public:
		GC()
		{
    
    

		}
		~GC()
		{
    
    
			if (CP2PMgr::p2pMgr)
				delete CP2PMgr::p2pMgr;
			CP2PMgr::p2pMgr = nullptr;
		}

	};

	static GC m_gc;
	static CP2PMgr* p2pMgr;
};

以上代码在多线程场景下最好不要使用,因为它并不是线程安全的,如需线程安全,最好是加锁控制!如下:

#pragma once

#include <mutex>
using namespace std;
class SingleTon_com_s
{
    
    
public:
	static SingleTon_com_s &GetInstance()
	{
    
    
		m_mutex.lock();
		static SingleTon_com_s ins;
		m_mutex.unlock();
		return ins;
	}
	SingleTon_com_s(const SingleTon_com_s &) = delete;
	SingleTon_com_s &operator=(const SingleTon_com_s &) = delete;
	virtual ~SingleTon_com_s() {
    
    }
	void test()
	{
    
    
		printf("hello world!");
	}
protected:
	SingleTon_com_s() {
    
    }

public:
	static std::mutex m_mutex;
};
std::mutex SingleTon_com_s::m_mutex; //静态一定要在外部初使化

总结

1. Windows的Task Manager(任务管理器)就是很典型的单例模式(这个很熟悉吧),想想看,是不是呢,你能打开两个windows task manager吗? 不信你自己试试看哦~
  1. windows的Recycle Bin(回收站)也是典型的单例应用。在整个系统运行过程中,回收站一直维护着仅有的一个实例。

猜你喜欢

转载自blog.csdn.net/kaizi318/article/details/109052225