Skip to content

Instantly share code, notes, and snippets.

@kaiyangjia
Created March 13, 2018 10:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaiyangjia/0f3ed31c74f29ceb3d78980ae5331b7c to your computer and use it in GitHub Desktop.
Save kaiyangjia/0f3ed31c74f29ceb3d78980ae5331b7c to your computer and use it in GitHub Desktop.
Better singleton implement for android/java platform. It's based on android.util.Singleton
public abstract class XSingleton<T> {
private T mInstance;
protected abstract T create();
/**
* is this object ready for work?
* That means is this object has been init by JVM.
* This method is design for The Double Checked Lock Broken
* (see this: https://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html )
*
* @return ready or not
*/
protected abstract boolean ready(T target);
public final T get() {
if (mInstance != null
&& ready(mInstance)) {
return mInstance;
}
synchronized (this) {
if (mInstance == null) {
mInstance = create();
}
return mInstance;
}
}
}
// usage for caller
public class SingletonFoo extends XSingleton<Foo> {
@Override
protected Foo create() {
return new Foo();
}
@Override
protected boolean ready(Foo target) {
return target.getFoo() != null;
}
}
// Target to be singled.
public class Foo {
private String foo;
public String getFoo() {
return foo;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment