1

我有 2 个事件的类:OnConnect 和 OnDisconnect:

type
    TEvent = reference to procedure;
    TConnection = class
    private
        fOnConnect: TEvent;
        fOnDisconnect: TEvent;
    public
        procedure SomeBehavior(aChoice: Boolean);
        property OnConnect: TEvent read fOnConnect write fOnConnect;
        property OnDisconnect: TEvent read fOnDisconnect write fOnDisconnect;
    end;

implementation

{ TConnection }

procedure TConnection.SomeBehavior(aChoice: Boolean);
begin
    if aChoice then
        fOnConnect
    else
        fOnDisconnect;
    //im not cheacking Assign(Events) to make example simple
end;

现在我想做同样的事情,但更多的对象风格。我的意思是使用 String4D 的接口和观察者模式。我做了这个:

interface

uses
    Spring.DesignPatterns;

type
    IObserver = interface
        procedure ReactToConnect(aText: String);
        procedure ReactToDisconnect(aTimeoutInMs: Integer);
    end;

    IConnection<T> = interface(IObservable<IObserver>)
        procedure SomeBehavior(aChoice: Boolean);
    end;

implementation

uses
    System.SysUtils;

type
    TConnection = class(TObservable<IObserver>, IConnection<IObserver>)
    public
        procedure SomeBehavior(aChoice: Boolean);
    end;

{ TConnection }

procedure TConnection.SomeBehavior(aChoice: Boolean);
var
    procOnConnect: TProc<IObserver>;
    procOnDisconnect: TProc<IObserver>; // what if i want no parameters?
    someText: String;
    someNumber: Integer;
begin
    someText := RandomText;
    procOnConnect := procedure(aObserver: IObserver)
                      begin
                          aObserver.ReactToConnect(someText);
                      end;
    someNumber := RandomInt;
    procOnDisconnect := procedure(aObserver: IObserver)
                         begin
                            aObserver.ReactToDisconnect(someNumber);
                         end;

    if aChoice then
        Self.NotifyListeners(procOnConnect)
    else
        Self.NotifyListeners(procOnDisconnect);

end;

我第一次这样做,只是想问一下它是否正确?或者我在这里做一些异端邪说?

4

0 回答 0