-
饿汉式
public class Singleton { private static final Singleton singleton=new Singleton(); public Singleton getInstance(){ return singleton; } }
-
懒汉式
class Singleton2{ private static Singleton2 mInstance ; public static Singleton2 getInstance(){ if (mInstance==null){ return new Singleton2(); } return mInstance; } }
-
方法加锁
class Singleton3{ private static Singleton3 mInstance; public static synchronized Singleton3 getInstance(){ if (mInstance==null){ mInstance= new Singleton3(); } return mInstance; } }
-
Double Check Lock(DCL)
class Singleton4{ private static Singleton4 mInstance; public static Singleton4 getInstance(){ if (mInstance==null){ synchronized(Singleton4.class){ mInstance= new Singleton4(); } } return mInstance; } }
-
静态内部类单例模式
class Singleton5{ private static Singleton5 getInstance(){ return Singleton5Holder.singleton5; } } class Singleton5Holder{ public static Singleton5 singleton5=new Singleton5(); }
网友评论