Created
June 30, 2023 10:46
-
-
Save maxgfr/bfece051fb2f106163ed765ca14841a2 to your computer and use it in GitHub Desktop.
A Singleton with multiple instance which returns the good instance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MultiSingletonHelper { | |
private static readonly instances: MultiSingletonHelper[] = []; | |
private readonly param1: string; | |
private readonly param2?: string; | |
private constructor(param1: string, param2?: string) { | |
this.param1 = param1; | |
this.param2 = param2; | |
} | |
public static getInstance( | |
param1: string, | |
param2?: string | |
): MultiSingletonHelper { | |
const existingInstance = MultiSingletonHelper.instances.find( | |
(instance) => instance.param1 === param1 && instance.param2 === param2 | |
); | |
if (existingInstance) { | |
return existingInstance; | |
} | |
const newInstance = new MultiSingletonHelper(param1, param2); | |
MultiSingletonHelper.instances.push(newInstance); | |
return newInstance; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment