-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimeLibraryFactory.ts
More file actions
83 lines (73 loc) · 1.83 KB
/
Copy pathTimeLibraryFactory.ts
File metadata and controls
83 lines (73 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import { ITimeLibrary } from './interfaces/ITimeLibrary';
import { MomentTimeLibrary } from './implementations/MomentTimeLibrary';
/**
* 时间库类型枚举
*/
export const TimeLibraryType = {
MOMENT: 'moment',
DAYJS: 'dayjs',
// XDATE: 'xdate',
// 可以继续添加其他时间库
// MOMENT: 'moment',
// DATE_FNS: 'date-fns'
} as const;
/**
* 时间库类型值
*/
export type TimeLibraryTypeValue = typeof TimeLibraryType[keyof typeof TimeLibraryType];
/**
* 时间库工厂
* 负责创建和管理不同的时间库实现
*/
class TimeLibraryFactory {
private currentType: TimeLibraryTypeValue;
private instance: ITimeLibrary | null;
constructor() {
this.currentType = TimeLibraryType.MOMENT;
this.instance = null;
this._createInstance();
}
/**
* 设置时间库类型
* @param type - 时间库类型
*/
setLibraryType(type: TimeLibraryTypeValue): void {
if (this.currentType !== type) {
this.currentType = type;
this._createInstance();
}
}
/**
* 获取当前时间库实例
* @returns 时间库实例
*/
getInstance(): ITimeLibrary {
if (!this.instance) {
throw new Error('Time library instance not initialized');
}
return this.instance;
}
/**
* 获取当前时间库类型
* @returns 时间库类型
*/
getCurrentType(): TimeLibraryTypeValue {
return this.currentType;
}
/**
* 创建时间库实例
* @private
*/
private _createInstance(): void {
switch (this.currentType) {
case TimeLibraryType.MOMENT:
this.instance = new MomentTimeLibrary();
break;
default:
throw new Error(`Unsupported time library type: ${this.currentType}`);
}
}
}
// 创建全局工厂实例
const timeLibraryFactory: TimeLibraryFactory = new TimeLibraryFactory();
export { timeLibraryFactory };