Created
June 12, 2020 03:23
-
-
Save haohaozaici/e550ad03caaabfa464e9c2b466ef9b58 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 饿汉式 | |
class Singleton { | |
private static final Singleton ourInstance = new Singleton(); | |
static Singleton getInstance() { | |
return ourInstance; | |
} | |
private Singleton() { | |
} | |
} | |
// 静态内部类 | |
class Singleton2 { | |
private Singleton2() { | |
} | |
public static Singleton2 getInstance() { | |
return Singleton2Holder.sInstance; | |
} | |
private static class Singleton2Holder { | |
private static final Singleton2 sInstance = new Singleton2(); | |
} | |
} | |
// 懒汉式 线程安全 | |
class Singleton3 { | |
private static Singleton3 sInstance; | |
private static final Object sLock = new Object(); | |
@NonNull | |
final Context mContext; | |
Singleton3(@NonNull Context context) { | |
mContext = context.getApplicationContext(); | |
} | |
@NonNull | |
public static Singleton3 getInstance(@NonNull Context context) { | |
synchronized (sLock) { | |
if (sInstance == null) { | |
sInstance = new Singleton3(context); | |
} | |
return sInstance; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment