Skip to content

Instantly share code, notes, and snippets.

@zddarova
Last active May 26, 2023 14:36
Show Gist options
  • Save zddarova/02d5dd7269d74b6c9cbf31dfa729937d to your computer and use it in GitHub Desktop.
Save zddarova/02d5dd7269d74b6c9cbf31dfa729937d to your computer and use it in GitHub Desktop.
Example why do we need service locators
const serviceLocator = <String, dynamic>{};
/// single place when we are setting up our dependancies
void setupServiceLocator() {
// could change service implementation here and it will be used in whole program
serviceLocator['CatFactService'] = CatFactServiceImpl();
}
void main() {
// setting up service locator at the start of the app
setupServiceLocator();
// getting instance of service from service locator
final CatFactService service = serviceLocator['CatFactService'];
// passing service to the function, that depends on it.
// It could be any implementation, coz they all implements the interface, not implementation.
printDataFromService(service);
}
/// method that relies on service interface
void printDataFromService(CatFactService service) async {
/// using service, not knowing what implementation are
final fact = await service.getCatFact();
final fact2 = await service.getCatFact();
print(fact);
print(fact2);
}
/// interface with list of methods that every service should have
abstract class CatFactService {
Future<String> getCatFact();
}
/// get from API
class CatFactServiceImpl implements CatFactService {
@override
Future<String> getCatFact() => Future<String>.value('Data from api');
}
/// mocked data
class CatFactServiceMocked implements CatFactService {
@override
Future<String> getCatFact() => Future<String>.value('mocked data');
}
/// from second api
class CatFactServiceFromAnotherServed implements CatFactService {
@override
Future<String> getCatFact() => Future<String>.value('Data from another api');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment