lintcode204 单例

单例 

 

单例 是最为最常见的设计模式之一。对于任何时刻,如果某个类只存在且最多存在一个具体的实例,那么我们称这种设计模式为单例。例如,对于 class Mouse (不是动物的mouse哦),我们应将其设计为 singleton 模式。

你的任务是设计一个 getInstance 方法,对于给定的类,每次调用 getInstance 时,都可得到同一个实例。

样例

在 Java 中:

A a = A.getInstance();
A b = A.getInstance();

a 应等于 b.

 1 class Solution {
 2 public:
 3     /**
 4      * @return: The same instance of this class every time
 5      */
 6     static Solution* getInstance() {
 7         // write your code here
 8         static Solution* one;
 9         if (one == NULL) {
10             one = new Solution();
11         }
12         return one;
13 
14     }
15 private:
16     Solution() {}
17 };
原文地址:https://www.cnblogs.com/gousheng/p/7688491.html