Singleton is a most widely used design pattern. If a class has and only has one instance at every moment, we call this design as singleton. For example, for class Mouse (not a animal mouse), we should design it in singleton.
You job is to implement a getInstance
method for given class, return the same instance of this class every time you call this method.
Example
In Java:
A a = A.getInstance();
A b = A.getInstance();
a should equal to b.
1 class Solution { 2 /** 3 * @return: The same instance of this class every time 4 */ 5 private static Solution instance; 6 7 private Solution(){ 8 } 9 public static synchronized Solution getInstance() { 10 // write your code here 11 if (instance == null){ 12 instance = new Solution(); 13 return instance; 14 } else { 15 return instance; 16 } 17 } 18 };