單例 是最爲最常見的設計模式之一。對於任何時刻,如果某個類只存在且最多存在一個具體的實例,那麼我們稱這種設計模式爲單例。例如,對於 class Mouse (不是動物的mouse哦),我們應將其設計爲 singleton 模式。
你的任務是設計一個 getInstance 方法,對於給定的類,每次調用 getInstance 時,都可得到同一個實例。
樣例
在 Java 中:
A a = A.getInstance();
A b = A.getInstance();
a 應等於 b.
代碼
class Solution {
/**
* @return: The same instance of this class every time
*/
private static Solution instance=new Solution();
public static Solution getInstance() {
// write your code here
return instance;
}
};