I'm trying to figure out the best way to distribute state changes to multiple forms which make up an application.
In my scenario, I have a number of hardware devices which are monitored by my application. As an example, one of the devices is a GPS device. Data from these devices come in and information is then stored in one big state object. As an example, GPS positions coming in are stored with both present and historic positions made available to the application.
The application has many different forms and windows available to the user. As an example, the GPS has a form which displays the visible satellites overhead, as well as a form displaying the signal-to-noise ratios and another showing the GPS track over time.
One solution I've considered is to using something like the Observer pattern on my state object. New forms subscribe to the state object and then receive push notifications when the state object changes (new GPS position forces a push to the forms, who then re-paint and re-update their own states).
IObserver = interface
procedure Update;
end;
IObservable = interface
procedure Subscribe(Observer : IObserver);
end;
TObserverForm = class(TForm, IObserver)
// ....
procedure Update;
begin
// State has changed, update
end;
end;
TApplicationState = class(IObservable);
private
FObservers : TList<IObserver>;
FPosition : TPoint;
public
procedure Subscribe(Observer : IObserver);
begin
FObservers.Add(Observer);
end;
procedure PushUpdate;
begin
foreach Observer in Observers
Observer.Update;
end;
property Position : TPoint read GetPosition write SetPosition;
procedure SetPosition(Pos : TPoint);
begin
FPosition : Pos;
// Notify all observers
Self.PushUpdate;
end;
end;
The above is a crude mock-up of what I'm considering. This relies on state calling Subscribe
on each TObserverForm that is created during the application life-cycle (and un-subscribing when they're destroyed).
I can't really see any downsides to this. This solution could be tailored somewhat so that the TObserverForms only update and react to certain types of push updates.
Is there something fundamental missing here? Are there more logical/simple solutions to this common problem?