这里的观察者实现是否存在内存泄漏?
也许我不太了解delphi,但是我想问你:
在这个网站:http://blogs.teamb.com/joannacarter/2004/06/30/690 我发现了一个基于iterface的观察者模式的实现。
在执行 Attach 时,会调用此:
procedure TSubject.Attach(Observer: IObserver);
begin
if fObservers = nil then
fObservers := TInterfaceList.Create;
fObservers.Add(AObserver);
Notify;
end;
并且在 detach 中它的代码
procedure TSubject.Detach(Observer: IObserver);
begin
if fObservers <> nil then
begin
fObservers.Remove(AObserver);
if fObservers.Count = 0 then
fObservers := nil;
end;
end;
应该是:
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;
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,不应该,因为正如 Bharat 所说,IInterface 会处理这个问题。请注意,在您引用的示例中,fObservers 被声明为 IInterfaceList。这是一个接口。 Delphi 中的接口变量类似于 C++ 中的智能指针,它们在赋值时自动调用 _Addref 和 _Release。
另一方面,如果 fObservers 被声明为 TInterfaceList,那么它将是一个对象,并且对象在赋值时不会执行任何特殊操作,因此调用 Free 是正确的。
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.
无需添加
fObservers.Free;
语句。IInterface
将负责添加和释放fObservers
。Delphi 使用
_AddRef 和_Release
来管理接口对象的生命周期。当您将接口引用分配给接口变量时,Delphi 会自动调用
_AddRef
。当变量超出范围时,Delphi 自动调用
_Release
。有关更多信息,请访问此链接。
There is no need to add
fObservers.Free;
statement.IInterface
will take care of adding and releasing thefObservers
.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.