Does the observer implementation have a memory leak?

I may not know delphi all this is good, however I want to ask you:

on this site: http://blogs.teamb.com/joannacarter/2004/06/30/690 I found an implementation of the observer pattern based on iterface.

when joining, there is a call:

procedure TSubject.Attach(Observer: IObserver);
begin
    if fObservers = nil then
      fObservers := TInterfaceList.Create;
    fObservers.Add(AObserver);
    Notify;
end;

and in disconnection has a 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 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;
+3
source share
2 answers

No need to add instructions fObservers.Free;. IInterfacewill take care of the addition and release fObservers.

Delphi uses _AddRef and _Releaseto control the lifetime of conjugated objects.

, Delphi _AddRef.

, Delphi _Release.

.

+5

, , , , IInterface . , fObservers IInterfaceList , . . Delphi ++, _Addref _Release .

fObservers TInterfaceList, , , , Free.

+6

Source: https://habr.com/ru/post/1771711/


All Articles