Last active
November 29, 2016 22:00
-
-
Save ortuagustin/f3699a395bcca49ba36bf3d2110bc281 to your computer and use it in GitHub Desktop.
SingletonService
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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