Title: A real singleton class implementation (Part I)
Question: How to implement a real singleton class that can have only one instance.
Answer:
The rules are :
- Only one instance created the thirst time it was used
- No possibility of user creation or destruction
- Released on application termination
- User can't create or destroy it like standard objects
The problems are :
- You can't put Create and Destroy method in protected or private
Why ?
Because, user can always use Create and Destroy method !
I think it's a lack in Delphi.
Use this class like this :
with (TMyStaticClass.GetInstance) do
begin
SampleProc;
a := Data;
end;
If you want a full clueanup instance for reinitialization, use :
TMyStaticClass.LeaveInstance;
The next call to TMyStaticClass.GetInstance return the new object.
If you yant a persistent object for the life of the application :
- Set LeaveInstance to protected (or private...)
- Call GetInstance in the initialization part
// **************************************************************************
// * Implementation of a real Delphi singleton object *
// **************************************************************************
unit Real_Singleton;
interface
type
TMyStaticClass = class(TObject)
private
FData : integer;
public
constructor Create;
destructor Destroy; override;
class function GetInstance : TMyStaticClass; virtual;
class procedure LeaveInstance; virtual;
procedure SampleProc;
public
property Data : integer read FData write FData;
end;
implementation
uses
SysUtils;
var
MyStaticClass : TMyStaticClass;
//------------------------------------------
constructor TMyStaticClass.Create;
begin
raise Exception.Create('Must use GetInstance to get object.')
end;
//------------------------------------------
destructor TMyStaticClass.Destroy;
begin
raise Exception.Create('Must use LeaveInstance to release object.')
end;
//------------------------------------------
class function TMyStaticClass.GetInstance : TMyStaticClass;
begin
if not Assigned(MyStaticClass) then
begin
MyStaticClass := NewInstance as TMyStaticClass;
// -- Code here to do intialization instance tasks
end;
result := MyStaticClass;
end;
//------------------------------------------
class procedure TMyStaticClass.LeaveInstance;
begin
if not Assigned(MyStaticClass) then Exit;
// -- Code here to do cleanup instance tasks
MyStaticClass.FreeInstance;
MyStaticClass := nil;
end;
procedure TMyStaticClass.SampleProc;
begin
// -- Do what you want...
end;
//------------------------------------------
initialization
finalization
TMyStaticClass.LeaveInstance;
end.