How would you implement this in D? (signals & slots)
Chris Wright via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Feb 2 09:35:25 PST 2016
On Tue, 02 Feb 2016 15:59:06 +0000, Atila Neves wrote:
> struct String1 { string s; }
> struct String2 { string s; }
I've seen this sort of thing before. A blogger I used to follow, Jeremy
Miller, implemented an event broker using this pattern. I don't like it.
It requires a new type for each event, and you have to defensively use
that pattern even if you only have one event at the moment. Every time I
implemented an event system, I've gone with named events and no special
type for their parameters.
With std.signals, you could do this:
struct Event(TArgs...) {
mixin Signal!TArgs;
}
class Foo {
Event!string usernameEntered;
Event!string passwordEntered;
Event!(long, string) someOtherEventHappened;
void enterPassword(string s) { passwordEntered.emit(s); }
void enterUsername(string s) { usernameEntered.emit(s); }
}
void main() {
auto o = new Observer;
auto f = new Foo;
f.usernameEntered.connect(&o.watch);
f.passwordEntered.connect(&o.watch);
f.enterUsername("adelhurst");
f.enterPassword("********");
}
More information about the Digitalmars-d-learn
mailing list