Skip to content

Instantly share code, notes, and snippets.

@dmikis
Created December 14, 2016 11:17
Show Gist options
  • Save dmikis/8f4130bfce7d9c75c1f242fc851dd5de to your computer and use it in GitHub Desktop.
Save dmikis/8f4130bfce7d9c75c1f242fc851dd5de to your computer and use it in GitHub Desktop.
class Delegator<T> {
protected delegate: T;
getDelegate() {
return this.delegate;
}
setDelegate(delegate: T) {
this.delegate = delegate;
}
}
interface FooDelegate {
barCalled(foo: Foo);
}
class AbstractFooDelegate implements FooDelegate {
public static readonly defaultInstance: AbstractFooDelegate = new AbstractFooDelegate();
barCalled(foo: Foo) {}
}
class Foo extends Delegator<FooDelegate> {
private _name: string;
constructor(name: string) { super(); this._name = name; this.delegate = AbstractFooDelegate.defaultInstance }
name(): string { return this._name }
bar(): void { this.delegate.barCalled(this) }
}
class ConcreteFooDelegate implements FooDelegate {
barCalled(foo: Foo) { console.log('Bar called on ' + foo.name()); }
}
const d = new ConcreteFooDelegate();
const f = new Foo('baz');
f.setDelegate(d);
console.log('Calling bar');
f.bar();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment