设计模式-单例模式(Singleton) (创建型模式)
//以下代码来源: 设计模式精解-GoF 23种设计模式解析附C++实现源码
//Singleton.h
#pragma once #include<iostream> class Singleton { public: static Singleton* Instance(); protected: Singleton(); private: static Singleton* _instance; };
//Singleton.cpp
#include"Singleton.h" #include<iostream> Singleton* Singleton::_instance = 0; Singleton::Singleton(){ std::cout << "Create A Singleton Instance." << std::endl; } Singleton* Singleton::Instance() { if (_instance == 0) _instance = new Singleton(); return _instance; }
//main.cpp
#include"Singleton.h" #include<iostream> int main(int args, char* argv) { Singleton* I = Singleton::Instance(); return 0; }