import { BundleLoader } from './BundleLoader'; /** * 统一的JSON配置加载器 * 提供类型安全的JSON配置加载功能 */ export class JsonConfigLoader { private static instance: JsonConfigLoader; private configCache: Map = new Map(); // JSON文件路径映射 private static readonly CONFIG_PATHS = { shop: 'shop', weapons: 'weapons', wall: 'wall', skills: 'skill', skillConfig: 'skill_config', enemies: 'enemies', ballPrice: 'ball_price_config', ballController: 'ballController' } as const; public static getInstance(): JsonConfigLoader { if (!JsonConfigLoader.instance) { JsonConfigLoader.instance = new JsonConfigLoader(); } return JsonConfigLoader.instance; } /** * 加载JSON配置文件 * @param configType 配置类型 * @param useCache 是否使用缓存 * @returns 配置数据 */ public async loadConfig( configType: keyof typeof JsonConfigLoader.CONFIG_PATHS, useCache: boolean = true ): Promise { try { // 检查缓存 if (useCache && this.configCache.has(configType)) { return this.configCache.get(configType) as T; } const configPath = JsonConfigLoader.CONFIG_PATHS[configType]; const bundleLoader = BundleLoader.getInstance(); const asset = await bundleLoader.loadDataJson(configPath); if (asset && asset.json) { const config = asset.json as T; // 缓存配置 if (useCache) { this.configCache.set(configType, config); } console.log(`[JsonConfigLoader] ${configType}.json 加载成功`); return config; } else { throw new Error(`配置文件 ${configType}.json 数据为空`); } } catch (error) { console.error(`[JsonConfigLoader] ${configType}.json 加载失败:`, error); return null; } } /** * 预加载多个配置文件 * @param configTypes 配置类型数组 */ public async preloadConfigs( configTypes: (keyof typeof JsonConfigLoader.CONFIG_PATHS)[] ): Promise { const loadPromises = configTypes.map(type => this.loadConfig(type)); await Promise.all(loadPromises); } /** * 清除缓存 * @param configType 可选,指定清除某个配置的缓存 */ public clearCache(configType?: keyof typeof JsonConfigLoader.CONFIG_PATHS): void { if (configType) { this.configCache.delete(configType); } else { this.configCache.clear(); } } /** * 重新加载配置 * @param configType 配置类型 */ public async reloadConfig( configType: keyof typeof JsonConfigLoader.CONFIG_PATHS ): Promise { this.clearCache(configType); return this.loadConfig(configType, true); } /** * 获取已缓存的配置 * @param configType 配置类型 * @returns 缓存的配置数据,如果不存在则返回null */ public getCachedConfig( configType: keyof typeof JsonConfigLoader.CONFIG_PATHS ): T | null { return this.configCache.get(configType) as T || null; } /** * 检查配置是否已缓存 * @param configType 配置类型 * @returns 是否已缓存 */ public isCached(configType: keyof typeof JsonConfigLoader.CONFIG_PATHS): boolean { return this.configCache.has(configType); } /** * 获取所有可用的配置类型 * @returns 配置类型数组 */ public getAvailableConfigTypes(): (keyof typeof JsonConfigLoader.CONFIG_PATHS)[] { return Object.keys(JsonConfigLoader.CONFIG_PATHS) as (keyof typeof JsonConfigLoader.CONFIG_PATHS)[]; } } // 导出类型定义 export type ConfigType = keyof typeof JsonConfigLoader['CONFIG_PATHS']; // 导出单例实例的便捷方法 export const jsonConfigLoader = JsonConfigLoader.getInstance();