【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

转载于:https://www.cnblogs.com/flipped/p/6852165.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值