Integrate logging system into Flutter app with service registration and testing setup
This commit is contained in:
@@ -1,5 +1,61 @@
|
||||
/// A Calculator.
|
||||
class Calculator {
|
||||
/// Returns [value] plus 1.
|
||||
int addOne(int value) => value + 1;
|
||||
library;
|
||||
|
||||
import 'package:fluttery/logger/logger.dart';
|
||||
import 'package:fluttery/src/logger/logger_impl.dart';
|
||||
import 'package:kiwi/kiwi.dart';
|
||||
|
||||
/// A class to manage services.
|
||||
class App {
|
||||
static final _AppService _appService = _AppService();
|
||||
|
||||
/// Registers a service with a factory function to instantiate the implementation.
|
||||
///
|
||||
/// This ensures that the implementation is created when the service is requested.
|
||||
///
|
||||
/// `implFactory` - A factory method to create the service implementation.
|
||||
static void registerService<T extends Service>(T Function() implFactory) {
|
||||
_appService.registerSingleton<T>(implFactory);
|
||||
}
|
||||
|
||||
/// Retrieves the registered service.
|
||||
///
|
||||
/// Returns an instance of the registered service.
|
||||
static T service<T extends Service>() {
|
||||
return _appService.resolve<T>();
|
||||
}
|
||||
|
||||
/// Registers the default services required by the application.
|
||||
static void registerDefaultServices() {
|
||||
registerService<Logger>(() => LoggerImpl());
|
||||
}
|
||||
}
|
||||
|
||||
/// Abstract class to represent a service.
|
||||
abstract class Service {}
|
||||
|
||||
/// Internal class to manage the registration and resolution of services.
|
||||
class _AppService {
|
||||
static _AppService? _singleton;
|
||||
|
||||
static final KiwiContainer _kiwi = KiwiContainer();
|
||||
|
||||
/// Factory constructor to ensure singleton instance of _AppService.
|
||||
factory _AppService() => _singleton ??= _AppService._();
|
||||
|
||||
/// Private constructor.
|
||||
_AppService._();
|
||||
|
||||
/// Registers a singleton service with a factory function to create the instance.
|
||||
///
|
||||
/// `serviceFactory` - A factory method to create the service implementation.
|
||||
void registerSingleton<T extends Service>(T Function() serviceFactory) {
|
||||
_kiwi.registerFactory<T>((c) => serviceFactory());
|
||||
}
|
||||
|
||||
/// Resolves and retrieves the registered service.
|
||||
///
|
||||
/// Returns an instance of the registered service.
|
||||
T resolve<T extends Service>() {
|
||||
return _kiwi.resolve<T>();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user