[fpc-devel] Recent added support for Observer pattern in FCL
Luiz Americo Pereira Camara
luizmed at oi.com.br
Tue Aug 28 17:17:17 CEST 2012
Em 28/8/2012 09:15, michael.vancanneyt at wisa.be escreveu:
>
>
> On Tue, 28 Aug 2012, Luiz Americo Pereira Camara wrote:
>
>>
>> Why not let TFPObservedOperation as integer and define constants.
>>
>> It could define a constant like ooUser = 32
>> Below ooUser is reserved for future default constants
>> Above ooUser could be added custom messages
>> This is how LCL messages works
>
> Exactly because it is not meant as a general messaging interface, and
> I want the interface to reflect this.
>
> There is a clear intended use case: Mainly notification of changes.
This is the purpose i intend to use (replace my implementation).
Basically is a tree structure that needs to be observed. To avoid
performance problems like having to parse all the tree when a change
occurs i defined actions when a Child is added, deleted or inserted.
To be clear what i would need to do with the current approach:
const
ChildAdded = 1;
type
TMyNotifyInfo = record
NType: Integer;
NData: Pointer;
end;
PMyNotifyInfo = ^TMyNotifyInfo;
//notify
procedure TMyObserved.Changed;
var
R: TMyNotifyInfo;
begin
R.NType := ChildAdded;
R.NData := ChildItemObject;
FPONotifyObservers(Self,ooCustom, at R);
end;
//observe
procedure TMyObserver.FPOObservedChanged(ASender : TObject; Operation :
TFPObservedOperation; Data : Pointer);
var
R: PMyNotifyInfo;
begin
if Operation = ooCustom then
begin
R := PMyNotifyInfo(Data);
if R^.Ntype = ChildAdded then
DoChildAdd(R^.NData);
end;
end;
compare with my proposed solution of defining the type as integer:
const
ooChildAdded = ooUser + 1;
//notify
procedure TMyObserved.Changed;
begin
FPONotifyObservers(Self, ooChildAdded, ChildItemObject);
end;
//observe
procedure TMyObserver.FPOObservedChanged(ASender : TObject; Operation :
TFPObservedOperation; Data : Pointer);
begin
if Operation = ooChildAdded then
begin
DoChildAdd(Data);
end;
end;
Simpler, less code, less memory use, extensible.
All that with just changing the TFPObservedOperation to a Integer or
word type
IMO such feature at a low level class should be usable in the most use
cases, otherwise it will have a half observer support.
My proposition does not increase complexity of the code, nor any type of
overhead with the above gains.
Can you point the drawbacks?
Luiz
More information about the fpc-devel
mailing list