Skip to content
Delphi

Interfaces y Conteo de Referencias

Definir interfaces con conteo automático de referencias.

#interface#reference-counting

Code

delphi
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;