Created
February 15, 2018 16:08
-
-
Save serbanghita/4c5d8de4c3e7c3309cf34ef8c18523da to your computer and use it in GitHub Desktop.
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
abstract class Subject { | |
protected observers: Observer[] = []; | |
public addObserver(observer: Observer) { | |
this.observers.push(observer); | |
} | |
public removeObserver(observer: Observer) { | |
let found = this.observers.indexOf(observer); | |
if (found !== -1) { | |
this.observers.splice(found, 1); | |
} | |
} | |
public notify(eventName: string) { | |
this.observers.forEach((observer) => { | |
observer.onNotify(this, eventName); | |
}); | |
} | |
} | |
abstract class Observer { | |
public abstract onNotify(entity: Subject, eventName: string); | |
} | |
/** | |
* Subject | |
*/ | |
class Entity extends Subject { | |
public init(achievements: Achievements, sound: Sound) { | |
this.addObserver(achievements); | |
this.addObserver(sound); | |
} | |
public update() { | |
this.notify("PLAYER_GOT_HURT"); | |
} | |
} | |
/** | |
* Observers | |
*/ | |
class Sound extends Observer { | |
public onNotify(entity: Entity, eventName: string) { | |
switch (eventName) { | |
case "PLAYER_GOT_HURT": | |
this.play(eventName); | |
break; | |
} | |
} | |
private play(eventName: string) { | |
console.log("play", eventName); | |
} | |
} | |
class Achievements extends Observer { | |
public onNotify(entity: Entity, eventName: string) { | |
switch (eventName) { | |
case "KILLED_10_NPCS": | |
this.unlock(eventName); | |
break; | |
case "PLAYER_GOT_HURT": | |
this.unlock(eventName); | |
break; | |
} | |
} | |
private unlock(achievementName: string) { | |
console.log("unlock", achievementName); | |
} | |
} | |
const a = new Achievements(); | |
const s = new Sound(); | |
const p = new Entity(); | |
p.init(a, s); | |
p.update(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment