zoukankan      html  css  js  c++  java
  • 设计模式学习笔记c++版——单例模式

    特别注意单例模式c++实现在main.cpp中引用的时候要去申明下:

    Singleton * Singleton::m_Instance = NULL; //定义性声明

    不然会报错:无法解析的外部符号 "private: static class Singleton * Singleton::m_Instance" 之类的。

    以下是一个很简单的单例模式的测试demo,这个模式并没有考虑并发的问题。如果是并发,可以考虑在创建对象的时候加锁

    stdafx.h

    #pragma once
    #include "targetver.h"
    #include <stdio.h>
    #include <tchar.h>
    #include <iostream>
    using namespace std;
    

    Singleton.h

    #pragma once
    #include "stdafx.h"
    class Singleton
    {
    public:
    	static Singleton * GetInstance();
    
    	void Add();
    	void MyPrint(string str);
    
    private:
    	Singleton();
    	~Singleton();
    
    	static Singleton * m_Instance;
    	int intNum;
    };
    

    Singleton.cpp

    #include "stdafx.h"
    #include "Singleton.h"
    
    Singleton* Singleton::GetInstance()
    {
    	if (m_Instance == NULL)
    	{
    		m_Instance = new Singleton();
    	}
    	return m_Instance;
    }
    
    void Singleton::MyPrint(string str)
    {
    	printf("%s
    ",str.c_str());
    }
    
    void Singleton::Add()
    {
    	intNum++;
    	printf("intNum=%d
    ", intNum);
    }
    
    Singleton::Singleton()
    {
    	intNum = 0;
    }
    
    Singleton::~Singleton()
    {
    }
    

     

    main.cpp

    // c++单例模式 2016/1/7 dgx
    
    #include "stdafx.h"
    #include "Singleton.h"
    
    Singleton * Singleton::m_Instance = NULL; //定义性声明 
    int main(int argc, char *argv[])
    {
    	Singleton *singletonObj = Singleton::GetInstance();
    	singletonObj->MyPrint("Hello Singleton!");
    	singletonObj->Add();
    
    	for (int i = 0; i < 10; i++)
    	{
    		Singleton * singletonObj2 = Singleton::GetInstance();
    		singletonObj2->Add();
    	}
    	
    	getchar();
    	return 0;
    }
    

     

  • 相关阅读:
    随手记录---transform 属性
    界面实例--图片布局在前端
    随手记录---jq如何判断当前元素是第几个元素
    PDF.Js的使用—javascript中前端显示pdf文件
    Jszip的使用和打包下载图片
    有关Canvas的一点小事—canvas和resize
    form input限制
    idea打war包正确姿势
    轻松建站神器!15个超精致的Bootstrap网站模板下载
    bootstrap教程
  • 原文地址:https://www.cnblogs.com/duguxue/p/5109436.html
Copyright © 2011-2022 走看看