Friday, May 06, 2005

Circular reference issue of IInterface Object: Delphi implementation

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
IParent = interface(IInterface)
['{0097DA7B-2A00-48EC-9E40-80FA7D443DD4}']
end;

IChild = interface(IInterface)
['{06284805-8F15-4221-B1FF-C43B872C4A14}']
function GetParent: IParent;
property Parent: IParent read GetParent;
end;

TChild = class(TInterfacedObject, IChild)
private
FOuter: pointer;
function GetParent: IParent;
public
constructor Create(const AOuter: IParent);
procedure BeforeDestruction; override;
end;

TParent = class(TInterfacedObject, IParent)
private
FChild: IChild;
public
procedure AfterConstruction; override;
end;

TForm1 = class(TForm)
private
FMyParent: TParent;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.AfterConstruction;
begin
inherited;
FMyParent := TParent.Create;
end;

procedure TForm1.BeforeDestruction;
begin
inherited;
FMyParent.Free;
end;

procedure TChild.BeforeDestruction;
begin
inherited;
ShowMessage('Child Free');
end;

constructor TChild.Create(const AOuter: IParent);
begin
inherited Create;
FOuter := pointer(AOuter);
end;

function TChild.GetParent: IParent;
begin
Result := IParent(FOuter);
end;

procedure TParent.AfterConstruction;
begin
inherited AfterConstruction;
FChild := TChild.Create(Self);
end;

end.

0 Comments:

Post a Comment

<< Home