blob: 52890fc0d6389e347791dbc06bbe2faa19bbb4e9 (
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
|
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<FooSingleton, ParamObject> HOLDER =
* new SingletonHolder<FooSingleton, ParamObject>() {
* @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;
}
protected abstract E create(I initializer);
}
|