Ensures a class has only one instance and provides a global point of access to it.
- Use when there must be exactly one instance of a class, and it must be accessible to clients from a well known point.
- Good when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.
Structure of the Singleton Pattern

Implementation of the Singleton Pattern
Two sample implementations are shown in TSingletonForm (uSingletonF.pas). The first one, returns a reference to allow the client class further control over the singleton instance. In this sample the Instance() class method acts as a well known point for clients to get a reference to the instance of TSingletonForm. This method acts as gatekeeper and it will only allow one instance of the class to be created.
type
TSingletonForm = class(TForm)
...
public
...;
class function Instance: TSingletonForm;
end;
implementation
{$R *.DFM}
var
SingletonFrm: TSingletonForm;
class function TSingletonForm.Instance: TSingletonForm;
begin
if not assigned(SingletonFrm) then
SingletonFrm := TSingletonForm.Create(Application);
result := SingletonFrm;
end;
The alternative implementation does the same thing but is presented using the Open() class method, which provides a single point of entry to TSingletonForm class and does not return an instance reference. In a production application, this method could take parameters to further initialize the singleton instance.
class procedure TSingletonForm.Open;
begin
Screen.Cursor := crHourglass;
try
if not assigned(SingletonFrm) then
SingletonFrm := TSingletonForm.Create(Application);
with SingletonFrm do
try
// do any form initialization here
Show;
except
on Exception do
begin
Free;
raise;
end;
end;
finally
Screen.Cursor := crDefault;
end;
end;
Both samples rely on a global reference (implementation scope) SingletonFrm to the instance of TSingletonForm. The SingletonFrm is used to provide lazy initialization or on-demand construction of the instance, since TSingletonForm is not created until the client class accesses one of its well known entry points (Instance() or Open()). In the destructor, the SingletonFrm reference is set back to nil.
destructor TSingletonForm.Destroy;
begin
SingletonFrm := nil;
inherited Destroy;
end;
The OnClose event handler calls Release(), which Frees the form instance by using an asynchronous windows message to allow all event handlers to complete safely.
procedure TSingletonForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Release;
end;