项目作者: VSoftTechnologies

项目描述 :
Weak References for delphi
高级语言: Pascal
项目地址: git://github.com/VSoftTechnologies/VSoft.WeakReferences.git
创建时间: 2011-12-12T02:00:44Z
项目社区:https://github.com/VSoftTechnologies/VSoft.WeakReferences

开源协议:

下载


VSoft.WeakReference

The idea behind this unit is provide a similar lifecycle to reference counted objects
in delphi as WeakReference does in .NET.

Reference counted objects in delphi have some limitations when it comes to circular references,
where for example TParent references it’s children (via IChild), and TChild references it’s parent
(via IParent). If we remove any external references to our IParent and IChild instances without first
getting the child to remove it’s reference to IParent, we would end up with orphaned objects. This
is because our IChild and IParent instances are holding references to each other, and thus they never
get releaseds.

Usage

Classes that can be weak referenced need to descend from TWeakReferencedObject.

  1. type
  2. TParent = class(TWeakReferencedObject, IParent)
  3. ...
  4. end;
  5. TChild = class(TInterfacedObject, IChild)
  6. private
  7. FParent : IWeakReference<IParent>;
  8. protected
  9. procedure SetParent(const parent : IParent);
  10. function GetParent : IParent;
  11. public
  12. property Parent : IParent read GetParent write SetParent;
  13. end;
  14. implementation
  15. procedure TChild.SetParent(const parent : IParent);
  16. begin
  17. if parent <> nil then
  18. FParent := TWeakReference<IParent>.Create(parent)
  19. else
  20. FParent := nil;
  21. end;
  22. function TChild.GetParent : IParent;
  23. begin
  24. result := nil
  25. if (FParent <> nil) and FParent.IsAlive then
  26. result := FParent.Data;
  27. end;

In the above example, if the Parent object is destroyed before the child, the weak reference to it in the child object will be marked as nil (so .IsAlive returns false).