std.pattern.. templated publisher subscriber pattern, adding events to collections
Rory McGuire
rmcguire at neonova.co.za
Tue Jul 6 23:30:19 PDT 2010
On Wed, 07 Jul 2010 00:47:32 +0200, BLS <windevguy at hotmail.de> wrote:
> Okay a bit better snippet than before. snippet should be almost
> functional..
>
> /*
> Hi,
> Andrei brings in the idea of std.pattern. Seems that this module is
> "stalled"; Unfortunately !
> However I would like to enhance collection classes (likewise
> dcollections) with a Publisher - Subscriber pattern (signal - slot, or
> observer pattern) , if you prefer)
> Hope the idea of enhancing collections with events become clear with the
> following snippet.
> !!! I am able to spend just a few hours a month with D programming.. in
> other words, please don't kill me :)
> Untested Draft code which requires a lot of help and ,more important,
> feedback from you.
>
> */
>
> struct publisherMsg(T) {
> T data;
> Action a;
> }
>
> mixin template Publisher(T) {
> private :
>
> enum Action = {INSERT, UPDATE, DELETE, READONLY};
> //alias typeof(this) PT;
>
> struct receiver {
> Object o;
> callback cb;
> }
>
> receiver[] subscriber;
>
> publisherMsg!(T) msg;
>
> alias void delegate(const ref msg) callback;
>
> void addSubscriber(object o, callback cb) {
> //subscriber ~= o;
> }
>
> void publish() {
> foreach (object o ; subscriber)
> {
> // create message and send message
>
> }
> }
> }
>
> mixin template Subscriber() {
> // see UndoList for implementation
> }
>
> final class Stack(T, bool observable = false ) {
> T[] data;
>
> static if (observable) mixin Observable!T;
>
> void push( T t) {
> data ~= t;
> publish(t, Action.INSERT);
> }
> T pop() {
> publish(t, Action.DELETE);
> //...
> }
> bool empty() {
>
> }
> T top() {
> publish(t, Action.READONLY);
> //...
> }
> size_t size() {
>
> }
> }
> // Undo list will receive every pushed or popped item -data and action)
> class UndoList(T) {
> private:
> T[] data;
>
> /// should be part of the sunscriber mixin templates.
> publisherMsg!T stackMessage;
>
> void delegate(const ref stackMessage) dg;
>
> alias Stack!(int) IntegerStack;
>
> IntegerStack intstack = new IntegerStack;
>
> private this() {
> dg = &this.feedback;
>
> // SUBBSCRIBE Stack(T) push and pop events.
> intstack.addSubscriber(this, dg);
>
> }
> public void feedback(const ref stackMessage msg ) {
> writefln("Action");
> }
> }
Hi Bjoern,
your mixin template should have "private { ... }" rather than "private:" I
believe the current way will make
everything that uses the mixin template private after its used.
More information about the Digitalmars-d-learn
mailing list