Skip to content

Instantly share code, notes, and snippets.

@xperiments
Created June 25, 2013 18:43
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 xperiments/5861137 to your computer and use it in GitHub Desktop.
Save xperiments/5861137 to your computer and use it in GitHub Desktop.
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