zoukankan      html  css  js  c++  java
  • 设计模式-单体模式(C++)

    设计模式-单体模式

    单体模式在使用非常方便,适合于单一的对象,例如全局对象的抽象使用。
    需要注意的是单体模式不可继承

    // 实现 Singleton.h
    #ifndef  __SINGLETON_H__
    #define __SINGLETON_H__
    
    class Singleton
    {
    public:
    	static Singleton* Instance()
    	{
    		if (nullptr == m_Instance)
    		{
    			m_Instance = new Singleton();
    		}
    		return m_Instance;
    	}
    
    	static void ClearInstance()
    	{
    		if (NULL != m_Instance)
    		{
    			delete m_Instance;
    			m_Instance = NULL;
    		}
    	}
    
    	void Print()
    	{
    		printf("hello world");
    	}
    
    private:
    	//Singleton模式,隐藏构造函数
    	Singleton()
    	{
    	}
    
    	~Singleton()
    	{
    	}
    
    	static Singleton* m_Instance;
    };
    
    Singleton* Singleton::m_Instance = nullptr;
    
    #endif
    
    // 使用 main.cpp
    #include "Singleton.h"
    int main()
    {
    	Singleton::Instance()->Print();
    	getchar();
    }
    
  • 相关阅读:
    3.学习Dispatcher
    2学习Application
    学习WPF-1
    Content-Type说明
    AspNet Core定时任务
    Asp.Net Core跨域配置
    学习Emmet
    Asp.Net Core存储Cookie不成功
    服务端编码和解码
    C#7特性
  • 原文地址:https://www.cnblogs.com/langzou/p/6097258.html
Copyright © 2011-2022 走看看