设计模式-创建型-单件
生活随笔
收集整理的這篇文章主要介紹了
设计模式-创建型-单件
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
#pragma once#ifndef SINGLETON_H #define SINGLETON_H
#include <memory>
using namespace std;
class Singleton
{
private: Singleton(){};
public:// 靜態(tài)成員函數(shù),提供全局訪問的接口 static Singleton* GetInstancePtr(); static Singleton GetInstance(); void Test();
protected: // 靜態(tài)成員變量,提供全局惟一的一個實例 static Singleton* m_pStatic;
}; #endif
#include "StdAfx.h" #include "singleton_impl.h" #include <iostream> // 類的靜態(tài)成員變量要在類體外進行定義 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; }
#include "StdAfx.h" #include "singleton_impl.h" #include <iostream> // 類的靜態(tài)成員變量要在類體外進行定義 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; }
總結
以上是生活随笔為你收集整理的设计模式-创建型-单件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 设计模式-创建型-生成器
- 下一篇: 设计模式-结构型-适配器