
个人理解
一句话,一个类有且仅有一个实例,单例模式也分懒汉式和恶汉式,看代码就可以了。
类图
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
package singleton; * 饿汉式单例模式 */ public class { private (){ } private static final HungrySingleton singleton=new HungrySingleton(); public static HungrySingleton getInstance(){ return singleton; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
package singleton; * 懒汉式单例模式 */ public class LazySingleton { private LazySingleton(){ } private static LazySingleton singleton=null; public static LazySingleton getInstance(){ if(singleton==null){ singleton=new LazySingleton(); } return singleton; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
package singleton; * Created by 张超 on 2017/4/9. */ public class Singleton { private Singleton(){ } private static Singleton singleton=null; public static Singleton getInstance(){ if(singleton==null){ synchronized (singleton){ if(singleton==null) singleton=new Singleton(); } } return singleton; } }
|
近期评论