优化
This commit is contained in:
77
lib/services/service_locator.dart
Normal file
77
lib/services/service_locator.dart
Normal file
@@ -0,0 +1,77 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import 'storage_service.dart';
|
||||
import 'notification_service.dart';
|
||||
import 'encouragement_service.dart';
|
||||
|
||||
/// Service Locator - 统一管理所有服务实例
|
||||
class ServiceLocator {
|
||||
static final ServiceLocator _instance = ServiceLocator._internal();
|
||||
factory ServiceLocator() => _instance;
|
||||
ServiceLocator._internal();
|
||||
|
||||
late StorageService _storageService;
|
||||
late NotificationService _notificationService;
|
||||
late EncouragementService _encouragementService;
|
||||
bool _isInitialized = false;
|
||||
|
||||
/// 初始化所有服务
|
||||
Future<void> initialize() async {
|
||||
if (_isInitialized) return;
|
||||
|
||||
try {
|
||||
// 初始化存储服务
|
||||
_storageService = StorageService();
|
||||
await _storageService.init();
|
||||
|
||||
// 初始化通知服务
|
||||
_notificationService = NotificationService();
|
||||
await _notificationService.initialize();
|
||||
await _notificationService.requestPermissions();
|
||||
|
||||
// 初始化鼓励语服务
|
||||
_encouragementService = EncouragementService();
|
||||
await _encouragementService.loadMessages();
|
||||
|
||||
_isInitialized = true;
|
||||
if (kDebugMode) {
|
||||
print('ServiceLocator initialized successfully');
|
||||
}
|
||||
} catch (e) {
|
||||
if (kDebugMode) {
|
||||
print('Failed to initialize ServiceLocator: $e');
|
||||
}
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
/// 获取存储服务实例
|
||||
StorageService get storageService {
|
||||
_checkInitialized();
|
||||
return _storageService;
|
||||
}
|
||||
|
||||
/// 获取通知服务实例
|
||||
NotificationService get notificationService {
|
||||
_checkInitialized();
|
||||
return _notificationService;
|
||||
}
|
||||
|
||||
/// 获取鼓励语服务实例
|
||||
EncouragementService get encouragementService {
|
||||
_checkInitialized();
|
||||
return _encouragementService;
|
||||
}
|
||||
|
||||
/// 检查服务是否已初始化
|
||||
void _checkInitialized() {
|
||||
if (!_isInitialized) {
|
||||
throw Exception('ServiceLocator has not been initialized yet. Call initialize() first.');
|
||||
}
|
||||
}
|
||||
|
||||
/// 重置服务(用于测试)
|
||||
void reset() {
|
||||
_isInitialized = false;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user