VSoft.WeakReferences
v0.1.5
このユニットの背後にあるアイデアは、Delphiでカウントされたオブジェクトを参照するのと同様のライフサイクルを提供することです。
Delphiのリファレンスカウントされたオブジェクトには、循環参照に関してはいくつかの制限があります。たとえば、Tparent References Its Children(ICHILDを介して)、およびTchild References Its As Parent(IParentを介して)。最初に子供にIPARENTへの参照を削除することなく、IPARENTおよびICHILDインスタンスへの外部参照を削除すると、孤立したオブジェクトになります。これは、私たちのICHILDとIPARENTのインスタンスが互いに言及されているため、リリースされることはないためです。
参照される可能性のあるクラスは、 TWeakReferencedObjectから下降する必要があります。
type
TParent = class(TWeakReferencedObject, IParent)
...
end;
TChild = class(TInterfacedObject, IChild)
private
FParent : IWeakReference<IParent>;
protected
procedure SetParent(const parent : IParent);
function GetParent : IParent;
public
property Parent : IParent read GetParent write SetParent;
end;
implementation
procedure TChild.SetParent(const parent : IParent);
begin
if parent <> nil then
FParent := TWeakReference<IParent>.Create(parent)
else
FParent := nil;
end;
function TChild.GetParent : IParent;
begin
result := nil
if (FParent <> nil) and FParent.IsAlive then
result := FParent.Data;
end;
上記の例では、親オブジェクトが子の前に破壊された場合、子オブジェクトへの弱い参照はnilとしてマークされます(isaliveはfalseを返します)。