單例 是最為最常見的設計模式之一。對于任何時刻,如果某個類只存在且最多存在一個具體的實例,那么我們稱這種設計模式為單例。例如,對于 class Mouse (不是動物的mouse哦),我們應將其設計為 singleton 模式。
你的任務是設計一個 getInstance 方法,對于給定的類,每次調用 getInstance 時,都可得到同一個實例。
樣例
在 Java 中:
A a = A.getInstance();
A b = A.getInstance();
a 應等于 b.
// 關于單例模式 要注意三點
//1. 一個類只能有一個對象,也就是說一定存在static 修飾的函數 或者對象
// 2. 不能隨意創建對象,所以類的拷貝,復制,賦值構造函數一定是是有的
//3. 既然static ,getInstance 是static 的函數,另外一個很重要的是一定有一個static 的對象 ,
//基本思路
// 使用的使用一定是這樣的
/*
int main(){
Solution * s=Solution :: getInstane () ;
}
getinstance 是屬于這個類的函數,不屬于任何對象。
*/
class Solution {
private:
static Solution * s;
Solution() {
s = NULL;
};
Solution(const Solution & s) {}; //復制構造函數
void operator = (const Solution &s) {}; //復制構造函數
public:
/**
* @return: The same instance of this class every time
*/
static Solution* getInstance() {
// write your code here
if (s == NULL) {
s = new Solution();
return s;
}
else {
return s;
}
}
};
//記得要加上這個
Solution * Solution::s = NULL;