【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
┆凉┆暖┆降┆等┆幸┆我┆我┆里┆将┆ ┆可┆有┆谦┆戮┆那┆ ┆大┆始┆ ┆然┆
┆薄┆一┆临┆你┆的┆还┆没┆ ┆来┆ ┆是┆来┆逊┆没┆些┆ ┆雁┆终┆ ┆而┆
┆ ┆暖┆ ┆如┆地┆站┆有┆ ┆也┆ ┆我┆ ┆的┆有┆精┆ ┆也┆没┆ ┆你┆
┆ ┆这┆ ┆试┆方┆在┆逃┆ ┆会┆ ┆在┆ ┆清┆来┆准┆ ┆没┆有┆ ┆没┆
┆ ┆生┆ ┆探┆ ┆最┆避┆ ┆在┆ ┆这┆ ┆晨┆ ┆的┆ ┆有┆来┆ ┆有┆
┆ ┆之┆ ┆般┆ ┆不┆ ┆ ┆这┆ ┆里┆ ┆没┆ ┆杀┆ ┆来┆ ┆ ┆来┆