Skip to content
Delphi

Interfaces and Reference Counting

Define interfaces with automatic reference counting.

By EZ4Code Team
interfacereference-counting

Code

type
  ILogger = interface
    ['{GUID-HERE}']  // Ctrl+Shift+G to generate
    procedure Log(const Msg: string);
    function GetLevel: Integer;
    property Level: Integer read GetLevel;
  end;

  TConsoleLogger = class(TInterfacedObject, ILogger)
  public
    procedure Log(const Msg: string);
    function GetLevel: Integer;
  end;

implementation

procedure TConsoleLogger.Log(const Msg: string);
begin
  WriteLn('[LOG] ' + Msg);
end;

function TConsoleLogger.GetLevel: Integer;
begin
  Result := 1;
end;

// Usage — reference counted
var
  Logger: ILogger;
begin
  Logger := TConsoleLogger.Create;
  Logger.Log('Hello');
  // No need to Free — ref-counted
end;

Explanation

Delphi interfaces use COM-style reference counting — when the last reference goes out of scope, the object is freed automatically. TInterfacedObject is the base class for ref-counted objects. Generate a GUID for each interface (used for QueryInterface). Mixing interface and object references to the same instance causes premature freeing.

More Delphi Snippets