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
Units and Classes
Define units with interface and implementation sections.
VCL Form Basics
Create a form with event handlers in Delphi VCL.
Properties and Events
Define properties and event handlers in Delphi.
Generics
Type-safe containers with generics in Delphi.
Exception Handling
Try/Except/Finally in Delphi.
RTTI (Runtime Type Information)
Inspect types and properties at runtime.