Singleton implementations include lazy, hungry, double check locks, enumerations, inner classes, etc., but I won’t list them all. Inadvertently found that while reading the Android source code a Singleton class/frameworks/base/core/Java/Android/util/Singleton. Java, can realize LanHanShi Singleton, writing is very strange, although is a hide, but copies will be ready to use.

package android.util;

/**
 * Singleton helper class for lazily initialization.
 *
 * Modeled after frameworks/base/include/utils/Singleton.h
 *
 * @hide* /
public abstract class Singleton<T> {
    private T mInstance;

    protected abstract T create(a);

    public final T get(a) {
        synchronized (this) {
            if (mInstance == null) {
                mInstance = create();
            }
            returnmInstance; }}}Copy the code

Normal slacker singleton

public class SingletonDemo {
    private static SingletonDemo mInstance;

    public static final SingletonDemo get() {
        synchronized (SingletonDemo.class) {
            if (mInstance == null) {
                mInstance = new SingletonDemo();
            }
            returnmInstance; }}}Copy the code

Slacker + double check singleton

public class SingletonDemo {
    private static SingletonDemo mInstance;

    public static final SingletonDemo get() {
        if (mInstance == null) {
            synchronized (SingletonDemo.class) {
                if (mInstance == null) {
                    mInstance = newSingletonDemo(); }}}returnmInstance; }}Copy the code

Mutant slacker singleton

public class SingletonDemo {

    public static final SingletonDemo get(a) {
        return INSTANCE.get(a);
    }

    private static final Singleton<SingletonDemo> INSTANCE = new Singleton<SingletonDemo>() {
        protected SingletonDemo create(a) {
            return newSingletonDemo(); }}; }Copy the code

The singleton. Java utility class does not perform double check (see Singleton. Java at Googlesource). This code was submitted 6 years ago), so we can add a double check optimization when copying singleton.java for use. Singleton.java encapsulates the create, GET template, and validation logic in GET so that the implementation code in SingletonDemo can be simpler: 1.create() a Singleton object, 2. Get () when needed.