##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
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.