maybe i dont know delphi all that well, however i wish to ask you:
at this site : http://blogs.teamb.com/joannacarter/2004/06/30/690 i found an implemetation of observer pattern based on iterface.
when doing attach , there is a call to this:
procedure TSubject.Attach(Observer: IObserver);
begin
if fObservers = nil then
fObservers := TInterfaceList.Create;
fObservers.Add(AObserver);
Notify;
end;
and in the detach it has the code
procedure TSubject.Detach(Observer: IObserver);
begin
if fObservers <> nil then
begin
fObservers.Remove(AObserver);
if fObservers.Count = 0 then
fObservers := nil;
end;
end;
should it be :
procedure TSubject.Detach(Observer: IObserver);
begin
if fObservers <> nil then
begin
fObservers.Remove(AObserver);
if fObservers.Count = 0 then begin
fObservers.Free;
fObservers := nil;
end;
end;
end;
No, it shouldn't, because as Bharat said, IInterface will take care of that. Note that fObservers is declared as IInterfaceList in the example you're reffering to. It's an interface. Interface variables in Delphi are akin to smart pointers in C++, they call _Addref and _Release on assignments automatically.
If fObservers was declared as TInterfaceList, on the other hand, then it would be an object, and objects don't do anything special on assignment, so it would have been correct to call Free.
There is no need to add fObservers.Free; statement. IInterface will take care of adding and releasing the fObservers .
Delphi uses _AddRef and _Release to manage the lifetime of interfaced objects.
When you assign an interface reference to an interface variable, Delphi automatically calls _AddRef.
When the variable goes out of scope, Delphi automatically calls _Release.
For more info go through this link.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With