【C++】实现一个简单的单例模式

💍 单例模式

现实例子

一个国家同一时间只能有一个总统。当使命召唤的时候,这个总统要采取行动。这里的总统就是单例的。

白话

确保指定的类只生成一个对象。

维基百科

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

单例模式其实被看作一种反面模式,应该避免过度使用。它不一定不好,而且确有一些有效的用例,但是应该谨慎使用,因为它在你的应用里引入了全局状态,在一个地方改变,会影响其他地方。而且很难 debug 。另一个坏处是它让你的代码紧耦合,而且很难仿制单例。

代码例子

要创建一个单例,先让构造函数私有,不能克隆,不能继承,然后创造一个静态变量来保存这个实例。

以下是饿汉模式:

game.h

#pragma once
class Game {
public:
        static Game* getInstance();//单例模式
        void start();
private:
        Game(){};
        Game(const Game&) {};
        Game &operator=(const Game&) {};
        static Game *instance;
}

game.cpp

#include <iostream>
#include "game.h"

Game* Game::instance = new Game;
Game* Game::getInstance() {
        return instance;
}
void Game::start(){
        std::cout<<"Game Start!"<<std::endl;
}

使用的时候:

#include "game.h"

int main() {
        Game *g = Game::getInstance();
        g->start();
        return 0;
}

参考:https://github.com/questionlin/design-patterns-for-humans

posted @ 2017-05-14 12:33  水郁  阅读(2304)  评论(0编辑  收藏  举报
……