Skip to content

Instantly share code, notes, and snippets.

@k33g
Created October 26, 2012 16:57
Show Gist options
  • Save k33g/3959903 to your computer and use it in GitHub Desktop.
Save k33g/3959903 to your computer and use it in GitHub Desktop.
Patterns & Typescript

##The Singleton Pattern

class SantaClaus {

	private static uniqueInstance : SantaClaus;
	
	public static getInstance() : SantaClaus {
		
		if(uniqueInstance == null) {
			console.log("Santa Claus, THE only one !!!")
			uniqueInstance = new SantaClaus(); 
		} else  {
			console.log("only one Santa Claus !!!")
		}
		return uniqueInstance;
	}
}

bob = SantaClaus.getInstance();
sam = SantaClaus.getInstance();

console.log (bob === sam);

###Result :

Santa Claus, THE only one !!!
only one Santa Claus !!!
true

##The Pattern Observer

interface Observer {
	update (arg:any);
}

class Observable { // or Interface
	private observers : Observer [];

	constructor() {
		this.observers = [];
	}

	registerObserver (observer : Observer) : void {
		this.observers.push(observer);
	}

	removeObserver (observer : Observer) : void {
		this.observers.splice(this.observers.indexOf(observer), 1);
	}

	notifyObservers (arg : any) : void {

		this.observers.forEach((observer : Observer)=> {
			observer.update(arg);
		});
	}
}


class Humanoid implements Observer {

	constructor(public name : string) {}

	update(arg:any) {
		console.log(this.name, " says : old value : ", arg.old, " new value : ", arg.new);
	}
}


class Human extends Observable {

	private name : string;

	constructor(name : string) {
		super();
		this.setName(name)
	}

	public getName() {
		return this.name;
	}

	public setName(name : string) {
		var old = this.name;
		this.name = name;
		this.notifyObservers({old:old, new:this.name});
	}
}

Peter = new Human("Peter");

September = new Humanoid("September");
December = new Humanoid("December");

Peter.registerObserver(September);
Peter.registerObserver(December);

Peter.setName("Peter Bishop");

Peter.removeObserver(December);

Peter.setName("Peter BISHOP");

###Result :

September  says : old value :  Peter  new value :  Peter Bishop
December  says : old value :  Peter  new value :  Peter Bishop
September  says : old value :  Peter Bishop  new value :  Peter BISHOP
@MrDesjardins
Copy link

Hello,
On your singleton example, you still need to access the uniqueInstance variable with the name of the variable:
SantaClaus.uniqueInstance since it is a static variable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment