Skip to content

Instantly share code, notes, and snippets.

@maxgfr
Created June 30, 2023 10:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxgfr/bfece051fb2f106163ed765ca14841a2 to your computer and use it in GitHub Desktop.
Save maxgfr/bfece051fb2f106163ed765ca14841a2 to your computer and use it in GitHub Desktop.
A Singleton with multiple instance which returns the good instance
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