Created
April 6, 2022 09:24
-
-
Save BarryDaBee/6b80600b9d0be29acef2e544a2ec0edb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void main() { | |
setupLocator(); | |
print(locator<String>()); | |
} | |
final locator = Locator(); | |
void setupLocator(){ | |
locator.registerSingleton<String>(()=>'Yello World'); | |
locator.registerSingleton<double>(()=>25.0); | |
} | |
typedef FactoryFunc<T> = T Function(); | |
///Simple service locator | |
class Locator{ | |
factory Locator() => _instance; | |
static final Locator _instance = Locator._internal(); | |
final Map<dynamic, dynamic> _items = {}; | |
Locator._internal(); | |
void registerSingleton<T extends Object>(FactoryFunc<T> factoryFunc){ | |
_items.putIfAbsent(T, factoryFunc); | |
} | |
T get<T>(){ | |
return _items[T]; | |
} | |
T call<T>(){ | |
return _items[T]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment