[fpc-devel] Recent added support for Observer pattern in FCL
michael.vancanneyt at wisa.be
michael.vancanneyt at wisa.be
Tue Aug 28 09:50:44 CEST 2012
On Mon, 27 Aug 2012, Luiz Americo Pereira Camara wrote:
> Back in 2010, in the thread about observer support in fcl, i asked if the
> actions would be customizable so i could, e.g., notify/observe if a child was
> added or removed in a tree structure. The answer was yes.
>
> Looking at the recent added support, it limit the actions (called operations)
> to 5 types
>
> TFPObservedOperation = (ooChanged,ooFree,ooAddItem,ooDeleteItem,ooCustom);
>
> I ask to change to a mechanism that could allow customizable operations (more
> than one)
That is why you have ooCustom.
>
>
> I'm asking that because i have implemented a similar mechanism that support
> operations like Load, ChildAdd, ChildDelete, ChildChange. I believe that more
> developers are in the same situation,i.e., using observer pattern to an
> action not handled by those 5 types. It would be helpful to use the native
> implementation otherwise i will have to keep(re-implement) the observer
> support over TPersistent.
That's why you have ooCustom and Data at your disposal.
I imagined 3 scenarios for this:
The first:
Procedure TmyObject.SomethingChanged;
Var
Rec : TMyOperationInfo; // Contains custom information about your operation.
begin
Rec.XYZ:=MoreInfo; // Set up as needed.
FPONotifyObservers(Self,ooCustom, at Rec);
end;
Or, you can do
Procedure TmyObject.SomethingChanged;
Var
Obj : TMyOperationInfo; // Contains custom information about your operation.
begin
Obj:=TMyOperationInfo.Create(MyParams);
try
FPONotifyObservers(Self,ooCustom,Pointer(Obj));
finally
Obj.free;
end;
end;
Procedure TmyObject.SomeThingChanged(APropName : String);
begin
FPONotifyObservers(Self,ooCustom,GetPropInfo(Self,APropName));
end;
But I think the additional Create/Free may be heavy. That is why I decided
on a data pointer, not an object. It allows to use records as well as
objects.
The last scenario was for property change notifications:
Procedure TmyObject.SomeThingChanged(Const APropName : String);
begin
FPONotifyObservers(Self,ooCustom,GetPropInfo(Self,APropName));
end;
This could be called from a property setter.
There are many ways to implement an observer pattern. It is always a balance
between lightweight and extensibility. I believe the implemented mechanism
is both: it does not require additional objects (and thus heap operations)
but does allow using them.
> BTW:
> The names of the TFPObservedOperation are not consistent:
> ooChanged is in preterit while others not
>
> ooChanged does not has Item suffix
It does not need one. The sender has changed, not an item in a list.
The 'Item'-s are for when sender is a list, and an item is added to the list.
(TList, TStringList, TCollection)
That's a matter of documentation.
Michael.
More information about the fpc-devel
mailing list