设计模式-创建型-单件

来源:互联网 发布:工程施工进度计划软件 编辑:程序博客网 时间:2024/06/04 00:46
#pragma once#ifndef SINGLETON_H #define SINGLETON_H #include <memory>using namespace std;class Singleton { private: Singleton(){}; public:// 静态成员函数,提供全局访问的接口 static Singleton* GetInstancePtr(); static Singleton  GetInstance(); void Test(); protected: // 静态成员变量,提供全局惟一的一个实例 static Singleton* m_pStatic; }; #endif 

#include "StdAfx.h"#include "singleton_impl.h"#include <iostream> // 类的静态成员变量要在类体外进行定义 Singleton* Singleton::m_pStatic = NULL; Singleton* Singleton::GetInstancePtr() {if (NULL == m_pStatic) { m_pStatic = new Singleton(); } return m_pStatic; } Singleton Singleton::GetInstance() { return *GetInstancePtr(); } void Singleton::Test() { std::cout << "Test!\n"; } 

// Singleton.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include "singleton_impl.h"#include <stdlib.h>//保证一个类仅有一个实例,并提供一个访问它的全局访问点。int _tmain(int argc, _TCHAR* argv[]){// 不用初始化类对象就可以访问了 Singleton::GetInstancePtr()->Test(); Singleton::GetInstance().Test(); system("pause");return 0;}

原创粉丝点击