LintCode-单例实现

单例模式:this

对于任什么时候刻,若是某个类只存在且最多存在一个具体的实例;因此单例模式须要具有几个条件:spa

一、本身对象的变量必须私有;线程

二、构造方法必须私有,不能从外部调用;code

三、实现线程锁;对象

 

 1 class Solution {
 2     /**
 3      * @return: The same instance of this class every time
 4      */
 5      private static Solution s = null ;
 6      private Solution(){};
 7     public static Solution getInstance() {
 8         // write your code here
 9         if(s==null){
10             synchronized(Solution.class){
11                 s= new Solution();
12             }
13         }
14         return s ;
15     }
16 }
相关文章
相关标签/搜索