OLD | NEW |
| (Empty) |
1 // | |
2 // Copyright 2014 Google Inc. All rights reserved. | |
3 // | |
4 // Use of this source code is governed by a BSD-style | |
5 // license that can be found in the LICENSE file or at | |
6 // https://developers.google.com/open-source/licenses/bsd | |
7 // | |
8 | |
9 part of charted.core.utils; | |
10 | |
11 typedef T ObjectCreator<T>(); | |
12 | |
13 /// Provides a registry and factory service. | |
14 /// | |
15 /// Registration: | |
16 /// ObjectFactory.register(“type”, () => { new TypeCreator(); }); | |
17 /// | |
18 /// Usage: | |
19 /// instance = ObjectFactory.create('type'); | |
20 class ObjectFactory<T> { | |
21 Map<String, ObjectCreator<T>> _components = {}; | |
22 | |
23 /// Register a component [creator] for [name]. | |
24 void register(String name, ObjectCreator<T> creator) { | |
25 _components[name] = creator; | |
26 } | |
27 | |
28 /// Create an instance for [name]. | |
29 T create(String name) { | |
30 if (!_components.containsKey(name)) { | |
31 throw new ArgumentError('Element $name not found in ComponentFactory'); | |
32 } | |
33 var creator = _components[name], | |
34 instance = creator(); | |
35 if (instance == null) { | |
36 throw new ArgumentError('Component $name initialization failed.'); | |
37 } | |
38 return instance; | |
39 } | |
40 } | |
OLD | NEW |