Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Typescript Singleton
module x
{
export class Singleton
{
private static _instance : Singleton;
constructor( singletonEnforcer:()=>void )
{
if( singletonEnforcer !== SingletonEnforcer )
{
throw new Error("Error: Instantiation failed: Use Singleton.getInstance() instead of new.");
}
}
public static getInstance() : Singleton
{
if(Singleton._instance == null)
{
Singleton._instance = new Singleton(SingletonEnforcer);
}
return Singleton._instance;
}
}
function SingletonEnforcer(){}
}
x.Singleton.getInstance();
/* V1 */
class SingletonDemo
{
private static instance:SingletonDemo;
private static allowInstantiation:Boolean;
public static getInstance():SingletonDemo
{
if (instance == null)
{
SingletonDemo.allowInstantiation = true;
SingletonDemo.instance = new SingletonDemo();
SingletonDemo.allowInstantiation = false;
}
return instance;
}
constructor()
{
if (!SingletonDemo.allowInstantiation) {
throw new Error("Error: Instantiation failed: Use SingletonDemo.getInstance() instead of new.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.