Design Patterns and Architecture
48.1 Patterns in Delphi
Class var + class function, or initialization/finalization in a unit
Class references (class of), TClassRegistry, RegisterClass/FindClass Abstract Factory / Builder
Interfaces + fluent methods returning Self or the interface
Events (of object), TMessageManager, Spring4D multicast events
Interfaces or anonymous methods (TFunc<>) TAction/TActionList, undo stacks with command objects Decorator / Proxy
Interface wrapping, TVirtualInterface (dynamic proxies) Wrapping VCL/FMX components or legacy APIs behind interfaces
Virtual/abstract methods in base classes (TThread.Execute)
GetEnumerator (for..in support), generic enumerators Double dispatch with overloaded Visit methods Repository / Unit of Work
Interfaces over FireDAC queries, ORM sessions Spring4D container (GlobalContainer.RegisterType<TService>.Implements<IService>) MVC / MVP / MVVM
DMVCFramework, Delphi MVVM (DSharp), passive views for VCL forms
// Custom enumerator: enables for..in over your class
type
TNumberRange = class
private
FStart, FFinish: Integer;
public type
TEnumerator = record
private
FCurrent, FFinish: Integer;
public
function MoveNext: Boolean;
property Current: Integer read FCurrent;
end;
public
constructor Create(AStart, AFinish: Integer);
function GetEnumerator: TEnumerator;
end;
function TNumberRange.TEnumerator.MoveNext: Boolean;
begin
Inc(FCurrent);
Result := FCurrent <= FFinish;
end;
function TNumberRange.GetEnumerator: TEnumerator;
begin
Result.FCurrent := FStart - 1;
Result.FFinish := FFinish;
end;48.2 Architecture
Separate concerns: UI (forms/frames) → presenters or view models → services (business logic) → repositories (FireDAC/ORM) → database. Keep logic out of event handlers.
Data modules for data access, frames for reusable UI, interfaces for boundaries, Spring4D for DI.
SOLID in Delphi: single-responsibility units, interfaces for dependency inversion, small focused interfaces, virtual methods for open/closed.
Multi-tier and service-oriented systems: REST servers (Horse, DMVC, RAD Server, mORMot) plus FMX/VCL clients, JSON DTOs, JWT auth.
Cross-platform code sharing: shared business units (no VCL/FMX dependencies), conditional compilation for platform services, IFMXxxService abstractions.