设计模式-单例模式(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;
}
posted @ 2019-12-20 20:36  fourmii  阅读(206)  评论(0编辑  收藏  举报