haxe:如何创建整洁的观察者模式原型

时间:2014-03-01 11:55:46

标签: macros observer-pattern haxe

我创建了简单的观察者原型:

class CObservable<T> {

    public function new() {
        mObservers = new Array<T>();
    }

    public function sign(aObserver:T):Bool {
        for (observer in mObservers)
            if (observer == aObserver)
                return false;
        mObservers.push(aObserver);
        return true;
    }

    private var mObservers:Array<T>;

}

使用一些回调函数创建接口:

interface IConcreteObserver {

    function onStart(aObservable:CConcreteObservable):Void;

    function onStop(aObservable:CConcreteObservable):Void;

    // ... more callbacks with same signature that differs only by names ...

}

然后我用一些具体的类扩展原型:

class CConcreteObservable extends CObservable<IConcreteObserver> {

    public function new() {
        super();
    }

    public function notifyStart():Void {
        for (observer in mObservers)
            observer.onStart(this);
    }

    public function notifyStop():Void {
        for (observer in mObservers)
            observer.onStop(this);
    }

    // ... more notify methods for every callback ...
    // ... more and more ...
    // ... and even more ...

}

所有这些复制粘贴对我来说都是不切实际的,特别是当我有十几个回调方法时。是否有任何巧妙的技巧来声明一个简单的notify方法,或者可能是原型中的宏,并将它们称为notify(onStart)notify(onStop)等等?

0 个答案:

没有答案