Created
March 13, 2018 10:18
-
-
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
This file contains hidden or 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
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