Debian Codegraph @

owner-site/site/docs/singleton.md

raw symbols SCIP
1 ---
2 layout: docs
3 title: Singleton
4 prev_section: event-support
5 next_section: crypto
6 permalink: /docs/singleton/
7 ---
8
9 It makes sense for the configuration for an application to be a sort of [Singleton](http://c2.com/cgi/wiki?SingletonPattern).
10
11 In the most common case, to instantiate a `Config` object, you would do:
12
13 ```java
14 MyConfig cfg = ConfigFactory.create(MyConfig.class);
15 ```
16
17 People tends to use this as:
18
19 ```java
20
21 class MyApp {
22 private static MyConfig cfg =
23 ConfigFactory.create(MyConfig.class);
24
25 public void doSomething() {
26 UserInterface ui = new UserInterface(cfg);
27 Model model = new Model(cfg);
28 ui.setModel(model);
29 // do something more with cfg...
30 }
31 }
32
33 ```
34
35 The problem is that, it may be not very practical to pass the `cfg` object inside complex applications,
36 and if you use the `ConfigFactory.create()` in multiple places you'll end up in having multiple instances of the
37 `cfg` objects. And this may not be what you need.
38
39 For instance, if you have a J2EE Web application, to have a config object inside your servlets, you should configure a
40 `ServletContextListener` in your `web.xml` and bind the configuration object to the `ServletContext`.
41
42 Then retrieve the `cfg` object in your servlets in the `init()` method.
43
44 Example:
45
46 ```java
47 public class MyServletContextListener
48 implements ServletContextListener {
49
50 public void contextInitialized(ServletContextEvent sce) {
51 MyConfig cfg = ConfigFactory.create(MyConfig.class);
52 sce.getServletContext()
53 .setAttribute("com.acme.foo.bar.MyConfig", cfg);
54 }
55
56 public void contextDestroyed(ServletContextEvent sce) {
57 sce.getServletContext()
58 .removeAttribute("com.acme.foo.bar.MyConfig");
59 }
60 }
61
62 // then in your servlets
63
64 public class MyServlet extends HttpServlet {
65 private MyConfig cfg = null;
66
67 public void init(ServletConfig config)
68 throws ServletException {
69 cfg = (MyConfig)config.getServletContext()
70 .getAttribute("com.acme.foo.bar.MyConfig");
71 }
72
73 public void destroy() {
74 cfg = null;
75 }
76
77 protected void doGet(HttpServletRequest req,
78 HttpServletResponse resp)
79 throws ServletException, IOException {
80
81 // do something with cfg;
82
83 }
84 }
85 ```
86
87 I don't dislike the above example, since it's a kind of
88 [**dependency injection**](http://c2.com/cgi/wiki?DependencyInjection) mechanism (you don't necessarily need a
89 framework to do [IoC](http://c2.com/cgi/wiki?InversionOfControl)) and I usually prefer this over Singletons
90 (See [SingletonsAreEvil](http://c2.com/cgi/wiki?SingletonsAreEvil)), but... this is still pretty much of code.
91 Boilerplate code. The kind of code OWNER is supposed to remove.
92
93 So, this is why a sort of Singleton has been provided: I called it `ConfigCache`, since it's a little bit more
94 than a mere (evil) Singleton. And this makes me feel a bit better about it :-)
95
96
97 The ConfigCache
98 ---------------
99
100
101 So, as we've seen many times before, you should be familiar with the `ConfigFactory`:
102
103 ```java
104 MyConfig instance = ConfigFactory.create(MyConfig.class);
105 ```
106
107 The same way you can use the new `ConfigCache`:
108
109 ```java
110 MyConfig instance = ConfigCache.getOrCreate(MyConfig.class);
111 ```
112
113 The difference is that, when using `ConfigFactory` a new instance of the `MyConfig` object is created every time,
114 instead when using the `ConfigCache`, instances are returned from an internal cache.
115
116 ```java
117 MyConfig firstFromFactory = ConfigFactory.create(MyConfig.class);
118 MyConfig secondFromFactory = ConfigFactory.create(MyConfig.class);
119 // firstFromFactory not same as secondFromFactory
120
121 MyConfig firstFromCache = ConfigCache.getOrCreate(MyConfig.class);
122 MyConfig secondFromCache = ConfigCache.getOrCreate(MyConfig.class);
123 // firstFromCache same as secondFromCache
124 ```
125
126 You can assign an `id` to an instance:
127
128 ```java
129 MyConfig firstFromCache = ConfigCache.getOrCreate("foo", MyConfig.class);
130 MyConfig secondFromCache = ConfigCache.getOrCreate("foo", MyConfig.class);
131 MyConfig thirdFromCache = ConfigCache.getOrCreate("bar", MyConfig.class);
132 // firstFromCache same as secondFromCache
133 // thirdFromCache not same as secodFromCache or firstFromCache
134 ```
135
136 The `id` is defined as `java.lang.Object`, but you can use a `String` such as a name, as in the above example.
137
138 In some cases, it may be useful list all configuration objects in an application, for instance for debugging. This can
139 be accomplished using the `ConfigCache.list()` method, which returns a set of the `id` objects in the cache. This set
140 can be used to iterate over all configuration objects in the cache, for instance as follows.
141
142 ```java
143 for (Object id : ConfigCache.list()) {
144 Config cfg = ConfigCache.get(id);
145 // do something
146 }
147 ```
148
149 As for the `ConfigFactory` you can pass a list of imports to `ConfigCache`. In fact the `ConfigCache` interface is
150 pretty similar to `ConfigFactory`:
151
152 ```java
153 public final class org.aeonbits.owner.ConfigCache {
154 public static <T extends Config> T getOrCreate(Class<? extends T> clazz, Map<?, ?>... imports);
155 public static <T extends Config> T getOrCreate(Factory factory, Class<? extends T> clazz, Map<?, ?>... imports);
156 public static <T extends Config> T getOrCreate(Object id, Class<? extends T> clazz, Map<?, ?>... imports);
157 public static <T extends Config> T getOrCreate(Factory factory, Object id, Class<? extends T> clazz, Map<?, ?>... imports);
158 public static <T extends Config> T get(Object id);
159 public static <T extends Config> T add(Object id, T config);
160 public static void clear();
161 public static <T extends Config> T remove(Object id);
162 }
163 ```
164
165 The ConfigCache is designed to be thread safe, so you don't have to worry about concurrent access.