does the observer implementation here has memory leak?

delphi, design-patterns, memory-leaks

Solution

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.

Problem

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; ```

Original source