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