equal
deleted
inserted
replaced
107 * The client can register a factory for lazy creation of the |
107 * The client can register a factory for lazy creation of the |
108 * instance. |
108 * instance. |
109 */ |
109 */ |
110 public static interface Factory<T> { |
110 public static interface Factory<T> { |
111 T make(Context c); |
111 T make(Context c); |
112 }; |
112 } |
113 |
113 |
114 /** |
114 /** |
115 * The underlying map storing the data. |
115 * The underlying map storing the data. |
116 * We maintain the invariant that this table contains only |
116 * We maintain the invariant that this table contains only |
117 * mappings of the form |
117 * mappings of the form |
118 * {@literal Key<T> -> T } |
118 * {@literal Key<T> -> T } |
119 * or |
119 * or |
120 * {@literal Key<T> -> Factory<T> } |
120 * {@literal Key<T> -> Factory<T> } |
121 */ |
121 */ |
122 private Map<Key<?>,Object> ht = new HashMap<Key<?>,Object>(); |
122 private Map<Key<?>,Object> ht = new HashMap<>(); |
123 |
123 |
124 /** Set the factory for the key in this context. */ |
124 /** Set the factory for the key in this context. */ |
125 public <T> void put(Key<T> key, Factory<T> fac) { |
125 public <T> void put(Key<T> key, Factory<T> fac) { |
126 checkState(ht); |
126 checkState(ht); |
127 Object old = ht.put(key, fac); |
127 Object old = ht.put(key, fac); |
164 public Context() {} |
164 public Context() {} |
165 |
165 |
166 /** |
166 /** |
167 * The table of preregistered factories. |
167 * The table of preregistered factories. |
168 */ |
168 */ |
169 private Map<Key<?>,Factory<?>> ft = new HashMap<Key<?>,Factory<?>>(); |
169 private Map<Key<?>,Factory<?>> ft = new HashMap<>(); |
170 |
170 |
171 public Context(Context prev) { |
171 public Context(Context prev) { |
172 kt.putAll(prev.kt); // retain all implicit keys |
172 kt.putAll(prev.kt); // retain all implicit keys |
173 ft.putAll(prev.ft); // retain all factory objects |
173 ft.putAll(prev.ft); // retain all factory objects |
174 ht.putAll(prev.ft); // init main table with factories |
174 ht.putAll(prev.ft); // init main table with factories |
175 } |
175 } |
176 |
176 |
177 /* |
177 /* |
178 * The key table, providing a unique Key<T> for each Class<T>. |
178 * The key table, providing a unique Key<T> for each Class<T>. |
179 */ |
179 */ |
180 private Map<Class<?>, Key<?>> kt = new HashMap<Class<?>, Key<?>>(); |
180 private Map<Class<?>, Key<?>> kt = new HashMap<>(); |
181 |
181 |
182 private <T> Key<T> key(Class<T> clss) { |
182 private <T> Key<T> key(Class<T> clss) { |
183 checkState(kt); |
183 checkState(kt); |
184 Key<T> k = uncheckedCast(kt.get(clss)); |
184 Key<T> k = uncheckedCast(kt.get(clss)); |
185 if (k == null) { |
185 if (k == null) { |
186 k = new Key<T>(); |
186 k = new Key<>(); |
187 kt.put(clss, k); |
187 kt.put(clss, k); |
188 } |
188 } |
189 return k; |
189 return k; |
190 } |
190 } |
191 |
191 |