summaryrefslogtreecommitdiffstats
path: root/src-ambient/com/android/phone/common/ambient/SingletonHolder.java
blob: bca6023a84770ba338cf3e89e3509cc74d29ce7b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.android.phone.common.ambient;

/**
 * Encapsulates a threadsafe singleton pattern.
 *
 * This class is designed to be used as a public constant, living within a class that has a private constructor.
 * It defines a {@link #create(I)} method that will only ever be called once, upon the first call of {@link #get(I)}.
 * That method is responsible for creating the actual singleton instance, and that instance will be returned for all
 * future calls of {@link #get(I)}.
 *
 * Example:
 * <code>
 *     public class FooSingleton {
 *         public static final SingletonHolder&lt;FooSingleton, ParamObject&gt; HOLDER =
 *                 new SingletonHolder&lt;FooSingleton, ParamObject&gt;() {
 *                     @Override
 *                     protected FooSingleton create(ParamObject param) {
 *                         return new FooSingleton(param);
 *                     }
 *                 };
 *
 *         private FooSingleton(ParamObject param) {
 *
 *         }
 *     }
 *
 *     // somewhere else
 *     FooSingleton.HOLDER.get(params).doStuff();
 * </code>
 * @param <E> The type of the class to hold as a singleton.
 * @param <I> A parameter object to use during creation of the singleton object.
 */
public abstract class SingletonHolder<E, I> {
    private E mInstance;
    private final Object LOCK = new Object();

    public final E get(I initializer) {
        if (null == mInstance) {
            synchronized (LOCK) {
                if (null == mInstance) {
                    mInstance = create(initializer);
                }
            }
        }

        return mInstance;
    }

    public final boolean isCreated() {
        synchronized (LOCK) {
            return mInstance != null;
        }
    }

    protected abstract E create(I initializer);
}