blob: 104c4ab12edae0e322d4846c846cc9082cbbcd01 (
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
|
package bjc.utils.services;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* A place to retrieve services from
*
* @author bjcul
*
*/
public class Bordello {
private static final Map<Class<?>, Object> services = new ConcurrentHashMap<>();
/**
* Retrieve the implementation of a given service.
*
* @param <T> The type of the service.
*
* @param interfaceClass The class of the service.
*
* @return The default implementation of the service.
*/
public static <T> T get(Class<T> interfaceClass) {
synchronized (interfaceClass) {
Object service = services.get(interfaceClass);
if (service == null) {
try {
Class<?> implementor = interfaceClass.getAnnotation(Implementor.class).value();
service = implementor.getDeclaredConstructor().newInstance();
services.put(interfaceClass, implementor);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
return interfaceClass.cast(service);
}
}
/**
* Set an implementation for a given service to be something other than the default.
*
* @param <T> The type of the service
*
* @param interfaceClass The class of the service
* @param implementor The alternate implementation for the service.
*/
public static <T> void set(Class<T> interfaceClass, T implementor) {
synchronized (interfaceClass) {
services.put(interfaceClass, implementor);
}
}
}
|