Skip to content

Instantly share code, notes, and snippets.

@jarroddavis68
Last active April 4, 2022 21:12
Show Gist options
  • Save jarroddavis68/87640e79121b48667201291b39d6799a to your computer and use it in GitHub Desktop.
Save jarroddavis68/87640e79121b48667201291b39d6799a to your computer and use it in GitHub Desktop.
Singleton Class Implementation
unit uSpSingleton;
interface
uses
System.SysUtils;
type
// 1. Add this unit to your project, then save-as a new unit file
// 2. Place cursor on TSpSingleton and press Ctrl+Shift+E to rename class
// 3. Place cursor on SpSingleton and press Ctrl+Shift+E to rename global var
// 4. Update { xxx } throughout unit with updated class name
// 5. Add custom code to your new singleton class and access via the global var
{ xxx }
TSpSingleton = class
private
class var Instance: TSpSingleton;
procedure DoFree;
class constructor Create;
class destructor Destroy;
public
class function Create: TSpSingleton;
class procedure Destroy;
class procedure Free;
procedure Test;
end;
var
SpSingleton: TSpSingleton = nil;
implementation
class constructor TSpSingleton.Create;
begin
SpSingleton := TSpSingleton.Create;
end;
class destructor TSpSingleton.Destroy;
begin
if TSpSingleton.Instance <> nil then
begin
TSpSingleton.Instance.DoFree;
end;
end;
procedure TSpSingleton.DoFree;
begin
if Instance <> nil then
begin
inherited Free;
Instance := nil;
end;
end;
class function TSpSingleton.Create: TSpSingleton;
begin
if (Instance = nil) then
Instance:= inherited Create as Self;
result:= Instance;
end;
class procedure TSpSingleton.Destroy;
begin
raise Exception.Create('Calling Destry is not allowed');
end;
class procedure TSpSingleton.Free;
begin
raise Exception.Create('Calling Free is not allowed');
end;
procedure TSpSingleton.Test;
begin
WriteLn('this is a test');
end;
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment