Created
July 18, 2014 06:18
-
-
Save maxgherman/ed812d0f6cb022b18235 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
interface IMessage<T> { | |
data : T; | |
} | |
interface IObserver<T> { | |
update(message : IMessage<T>) : void; | |
unregister() : void; | |
unregisterAction : () => void; | |
} | |
class Observer<T> implements IObserver<T> { | |
public unregisterAction; | |
public update(message : IMessage<T>) {} | |
public unregister() { | |
this.unregisterAction(); | |
} | |
} | |
class Observable<T> { | |
private observers : Array<IObserver<T>>; | |
constructor() { | |
this.observers = []; | |
} | |
public constractMessage(callBack : (message : IMessage<T>) => void) : void { | |
callBack({ data : undefined }); | |
} | |
public register(observer :IObserver<T>) : void { | |
observer.unregisterAction = () => this.unregister(observer); | |
this.observers.push(observer); | |
} | |
public unregister(observer :IObserver<T>) : void { | |
this.observers.splice(this.observers.indexOf(observer), 1); | |
} | |
public notify() : void { | |
this.constractMessage(message => { | |
this.observers.forEach(item => item.update(message)); | |
}); | |
} | |
} | |
class Mail implements IMessage<string> | |
{ | |
public data : string; | |
} | |
class Postman extends Observable<string> { | |
public constractMessage(callBack : (message : IMessage<string>) => void) : void { | |
setTimeout(() => callBack({ data : "You've got delivery" }), 1000); | |
} | |
} | |
class Client extends Observer<string> { | |
public update(message : Mail) : void { | |
alert(message.data); | |
} | |
} | |
// ----- execution ----- | |
var client = new Client(); | |
var postman = new Postman(); | |
postman.register(client); | |
postman.notify(); | |
setTimeout(() => { | |
client.unregister(); | |
postman.notify(); | |
}, 2000); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment