我想TParent通过使用聚合构建一个包含多个子对象的类.有些对象是独立的,有些也可能依赖于其他孩子.所有子对象都必须具有对父对象的引用.我也想尽可能使用接口.
为此我使用TInterfacedObject的TParent并TAggregatedObject为孩子.由于孩子和父母都知道彼此,我使用弱引用以避免循环依赖.事实上,这种行为已经在中定义TAggregatedObject.当我只使用独立的子对象(TIndependantChild)时,一切正常.
当子对象也依赖于其他孩子时会出现问题,请参阅构造函数TDependantChild.我将引用存储在fChild变量中的另一个子对象中,该变量用[weak]Delphi 10 Berlin中引入的attibute标记.FastMM4报告关机时的内存泄漏:
此外,访问违规会导致System.TMonitor.Destroy加注,但只有当FastMM4处于使用状态并且ReportMemoryLeaksOnShutDown为True时才会发生这种情况.
program Project1;
{$APPTYPE CONSOLE}
uses
FastMM4,
System.SysUtils;
type
IParent = interface
['{B11AF925-C62A-4998-855B-268937EF30FB}']
end;
IChild = interface
['{15C19A4E-3FF2-4639-8957-F28F0F44F8B4}']
end;
TIndependantChild = class(TAggregatedObject, IChild)
end;
TDependantChild = class(TAggregatedObject, IChild)
private
[weak] fChild: IChild;
public
constructor Create(const Controller: IInterface; const AChild: IChild); reintroduce;
end;
TParent = class(TInterfacedObject, IParent)
private
fIndependantChild: TIndependantChild;
fDependantChild: TDependantChild;
public
constructor Create;
destructor Destroy; override; …Run Code Online (Sandbox Code Playgroud)