Instantiating a class that implements an interface

Giganews Newsgroups
Subject:Instantiating a class that implements an interface
Posted by: Rory Slegtenhorst
Date:Tue, 29 Sep 2009

Dear List,

I'm creating a "object holder" class that would destroy it's holded object after a certain time period had been reached, and no references to it's holded object remain but it's own.

Frantically I go around and create the basic object and it's holder. In a single unit where I call the class constructor directly. To keep things simple, I expose the use of the holded object through an interface and a singleton construction method.

Very happy that things work out just fine, and I realize I could use this code in a more generic sence, so I try to seperate the holder object from the actual object and come up with the following:

  TObjectHolder = class(TTimer)
  private
    FIntf: TInterfacedObject;
    FIntfClass: TInterfacedClass;
    function GetIntf: IInterface;
    procedure OnCustomTimer(Sender: TObject);
  public
    constructor Create(AInterfacedClass: TInterfacedClass); reintroduce;
    destructor Destroy; override;
    property Intf: IInterface read GetIntf;
  end;

function TObjectHolder.GetIntf: IInterface;
begin
  Enabled := False;
  if not Assigned(FIntf) then begin
    FIntf := FIntfClass.Create; // For some reason this doesn't work!
    IInterface(FIntf)._AddRef;
  end;
  Result := FIntf;
  Enabled := True;
end;

Personally I thought this "should" have worked, as it does with ordinary classes descending from TObject. I have done this many times before using other "class of" types, and was obviously stumped as to why my create constructor of type FIntfClass wasn't being called. :D
Shamely, google wasn't being very friendly either, and no good articles explaining the "behind the scenes" could be found :(

I hope someone can shed some light on what I can do to make this work...

Thanks in advance for any advise :D
djBo

Replies