Use singleton design pattern directly in the worker object factory
[e-mobility-charging-stations-simulator.git] / src / worker / WorkerFactory.ts
1 import { WorkerOptions, WorkerProcessType } from '../types/Worker';
2
3 import Constants from '../utils/Constants';
4 import WorkerAbstract from './WorkerAbstract';
5 import WorkerDynamicPool from './WorkerDynamicPool';
6 import WorkerSet from './WorkerSet';
7 import WorkerStaticPool from './WorkerStaticPool';
8 import { isMainThread } from 'worker_threads';
9
10 export default class WorkerFactory {
11 private static workerImplementation: WorkerAbstract | null;
12
13 private constructor() {}
14
15 public static getWorkerImplementation<T>(workerScript: string, workerProcessType: WorkerProcessType, options?: WorkerOptions, forceInstantiation = false): WorkerAbstract | null {
16 if (!isMainThread) {
17 throw new Error('Trying to get a worker implementation outside the main thread');
18 }
19 if (!WorkerFactory.workerImplementation || forceInstantiation) {
20 options = options ?? {} as WorkerOptions;
21 options.startDelay = options.startDelay ?? Constants.WORKER_START_DELAY;
22 WorkerFactory.workerImplementation = null;
23 switch (workerProcessType) {
24 case WorkerProcessType.WORKER_SET:
25 options.elementsPerWorker = options.elementsPerWorker ?? Constants.DEFAULT_CHARGING_STATIONS_PER_WORKER;
26 WorkerFactory.workerImplementation = new WorkerSet<T>(workerScript, options.elementsPerWorker, options.startDelay);
27 break;
28 case WorkerProcessType.STATIC_POOL:
29 options.poolMaxSize = options.poolMaxSize ?? Constants.DEFAULT_WORKER_POOL_MAX_SIZE;
30 WorkerFactory.workerImplementation = new WorkerStaticPool<T>(workerScript, options.poolMaxSize, options.startDelay, options.poolOptions);
31 break;
32 case WorkerProcessType.DYNAMIC_POOL:
33 options.poolMinSize = options.poolMinSize ?? Constants.DEFAULT_WORKER_POOL_MIN_SIZE;
34 options.poolMaxSize = options.poolMaxSize ?? Constants.DEFAULT_WORKER_POOL_MAX_SIZE;
35 WorkerFactory.workerImplementation = new WorkerDynamicPool<T>(workerScript, options.poolMinSize, options.poolMaxSize, options.startDelay, options.poolOptions);
36 break;
37 }
38 }
39 return WorkerFactory.workerImplementation;
40 }
41 }