Best way to implement observer pattern in Delphi

I found various implementations of the observer pattern in Delphi, for example: Sourcemaking Design Patterns and Delphi hobbies .

In general, what is the best way to implement an observer in Delphi?
I would say using interfaces because the code is more readable.

+6
oop design-patterns delphi
source share
2 answers

There is no “good” or “better” way to implement templates.
The implementation you choose depends on how you want to use it.

You can also use the generics function (available since Delphi 2009) to simplify the use of multiple templates.

And if you use Pre Delphi-3 versions or want to avoid reference counting , you cannot use interfaces.
(Link counting can open up a new can of worms when mixed with traditional owner / owner based life time management, remember to go down from classes that expose interfaces from the right ancestor, like TInterfacedObject - and watch your life time).

Besides the “clean” question of how to implement the observer pattern, it’s good to also be able to recognize classes in Delphi that implement the observer pattern.

For example, TDataSet / TDataSource also implements an observer pattern .
The whole concept of Data Aware Controls depends on it, everything is connected through TDataLink .

I wrote a TDataLink -based TDataLink component that reflects all the virtual methods in TDataLink for events in TDataLinkReflector .

Base on TDataLinkReflector I wrote TDataAwareControlController components that do all the interesting things for Data Aware Controls based on TDataSet, its TFields and TDataSource, associated with TDataSet (read-only coloring, required, etc.).

But even a seemingly simple thing, for example, events, can be considered as based on this template (although events are single events, so only one observer can observe one event).

Another class that implements this is TApplicationEvents ; Each instance allows you to listen to any of the events in TApplication.

Hope to shed some light on where observer patterns are used in Delphi.

- Jeroen

PS: Anyone interested in the components that I wrote may want to see the CodeRage video mentioned here .

+7
source share
+2
source share

All Articles