現實例子ios
一個國家同一時間只能有一個總統。當使命召喚的時候,這個總統要採起行動。這裏的總統就是單例的。git
白話github
確保指定的類只生成一個對象。函數
維基百科debug
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.rest
單例模式其實被看做一種反面模式,應該避免過分使用。它不必定很差,並且確有一些有效的用例,可是應該謹慎使用,由於它在你的應用裏引入了全局狀態,在一個地方改變,會影響其餘地方。並且很難 debug 。另外一個壞處是它讓你的代碼緊耦合,並且很難仿製單例。code
代碼例子對象
要建立一個單例,先讓構造函數私有,不能克隆,不能繼承,而後創造一個靜態變量來保存這個實例。繼承
如下是餓漢模式:get
#pragma once class Game { public: static Game* getInstance();//單例模式 void start(); private: Game(){}; Game(const Game&) {}; Game &operator=(const Game&) {}; static Game *instance; }
#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