122 public <T> void put(Key<T> key, Factory<T> fac) { |
122 public <T> void put(Key<T> key, Factory<T> fac) { |
123 checkState(ht); |
123 checkState(ht); |
124 Object old = ht.put(key, fac); |
124 Object old = ht.put(key, fac); |
125 if (old != null) |
125 if (old != null) |
126 throw new AssertionError("duplicate context value"); |
126 throw new AssertionError("duplicate context value"); |
|
127 checkState(ft); |
|
128 ft.put(key, fac); // cannot be duplicate if unique in ht |
127 } |
129 } |
128 |
130 |
129 /** Set the value for the key in this context. */ |
131 /** Set the value for the key in this context. */ |
130 public <T> void put(Key<T> key, T data) { |
132 public <T> void put(Key<T> key, T data) { |
131 if (data instanceof Factory<?>) |
133 if (data instanceof Factory<?>) |
140 public <T> T get(Key<T> key) { |
142 public <T> T get(Key<T> key) { |
141 checkState(ht); |
143 checkState(ht); |
142 Object o = ht.get(key); |
144 Object o = ht.get(key); |
143 if (o instanceof Factory<?>) { |
145 if (o instanceof Factory<?>) { |
144 Factory<?> fac = (Factory<?>)o; |
146 Factory<?> fac = (Factory<?>)o; |
145 o = fac.make(); |
147 o = fac.make(this); |
146 if (o instanceof Factory<?>) |
148 if (o instanceof Factory<?>) |
147 throw new AssertionError("T extends Context.Factory"); |
149 throw new AssertionError("T extends Context.Factory"); |
148 Assert.check(ht.get(key) == o); |
150 Assert.check(ht.get(key) == o); |
149 } |
151 } |
150 |
152 |
156 return Context.<T>uncheckedCast(o); |
158 return Context.<T>uncheckedCast(o); |
157 } |
159 } |
158 |
160 |
159 public Context() {} |
161 public Context() {} |
160 |
162 |
|
163 /** |
|
164 * The table of preregistered factories. |
|
165 */ |
|
166 private Map<Key<?>,Factory<?>> ft = new HashMap<Key<?>,Factory<?>>(); |
|
167 |
|
168 public Context(Context prev) { |
|
169 kt.putAll(prev.kt); // retain all implicit keys |
|
170 ft.putAll(prev.ft); // retain all factory objects |
|
171 ht.putAll(prev.ft); // init main table with factories |
|
172 } |
|
173 |
|
174 /* |
|
175 * The key table, providing a unique Key<T> for each Class<T>. |
|
176 */ |
161 private Map<Class<?>, Key<?>> kt = new HashMap<Class<?>, Key<?>>(); |
177 private Map<Class<?>, Key<?>> kt = new HashMap<Class<?>, Key<?>>(); |
162 |
178 |
163 private <T> Key<T> key(Class<T> clss) { |
179 private <T> Key<T> key(Class<T> clss) { |
164 checkState(kt); |
180 checkState(kt); |
165 Key<T> k = uncheckedCast(kt.get(clss)); |
181 Key<T> k = uncheckedCast(kt.get(clss)); |