Skip to content

Instantly share code, notes, and snippets.

@ortuagustin
Last active November 29, 2016 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ortuagustin/f3699a395bcca49ba36bf3d2110bc281 to your computer and use it in GitHub Desktop.
Save ortuagustin/f3699a395bcca49ba36bf3d2110bc281 to your computer and use it in GitHub Desktop.
SingletonService
unit Service;
type
IService = interface
procedure DoServiceThing;
end;
TFactory<T> = reference to function: T;
unit ServiceImpl;
uses
Service;
type
TServiceImpl = class(TInterfacedObject, IService)
strict private
procedure DoServiceThing;
end;
unit Globals;
uses
Service;
type
TGlobalService = record
strict private
class var FService: IService;
class var FServiceFactory: TFactory<IService>;
class function GetService: IService; static; inline;
class function GetServiceFactory: TFactory<IService>; static; inline;
class procedure SetServiceFactory(const Value: TFactory<IService>); static; inline;
public
class property Service: IService read GetService;
class property ServiceFactory: TFactory<IService> read GetServiceFactory write SetServiceFactory;
end;
implementation
uses
System.SysUtils;
class function TGlobalService.GetService: IService;
begin
if not Assigned(FService) then
begin
if not Assigned(FServiceFactory) then
raise EArgumentNilException.Create('ServiceFactory');
FService := FServiceFactory();
end;
Result := FService;
end;
class function TGlobalService.GetServiceFactory: TFactory<IService>;
begin
Result := FServiceFactory;
end;
class procedure TGlobalService.SetServiceFactory(const Value: TFactory<IService>);
begin
FServiceFactory := Value;
end
// consumer code
begin
// initialization
TGlobalService.ServiceFactory := function: IService
begin
Result := TServiceImpl.Create;
end;
// somewhere latter...
TGlobalService.Service.DoServiceThing;
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment