コメントで既に書いたように、この場合、他のサービスへのアクセスを提供できる 1 つのメインサービス(メイン クラス、シングルトン) を使用することをお勧めします。すべてのモジュールには一意の ID ( TGUID
) があります。プログラム実行の開始時に、メイン サービスに自分自身を登録する必要があります。
例えば。メイン サービス ユニット:
unit AppServices;
interface
uses generics.collections, rtti;
type
// Unique ID Attribute for services
ServiceIDAttribute = class(TCustomAttribute)
strict private
FId : TGUID;
public
constructor Create(ServiceID: string);
property ID : TGUID read FId;
end;
//Services Base class
TCustomAppService = class(TObject)
strict protected
public
end;
// Main Service Object
TAppServices = class(TObject)
strict private
class var
FServices : TObjectDictionary<TGUID, TCustomAppService>;
var
public
class constructor Create();
class destructor Destroy();
class procedure RegisterService(aService : TCustomAppService);
class function QueryService(ServiceID : TGUID):TCustomAppService;
end;
here class constructor
&単純にDictionarydestructor
を作成して解放し ます。メソッドは、一意の ID で Service を返します。FServices
QueryService
class function TAppServices.QueryService(ServiceID: TGUID): TCustomAppService;
begin
result := nil;
if FServices.ContainsKey(ServiceID) then
result := FServices[ServiceID];
end;
メソッドは、パラメーターのクラス名から属性 ( ) をRegisterService
抽出し、このペア (id-service) を辞書に追加します。RTTI
ServciceIDAttribute
class procedure TAppServices.RegisterService(aService: TCustomAppService);
var ctx : TRttiContext;
st : TRttiType;
a : TCustomAttribute;
id : TGUID;
begin
ctx := TRttiContext.Create();
try
st := ctx.GetType(aService.ClassType);
for a in st.GetAttributes() do begin
if not (a is ServiceIDAttribute) then
continue;
id := ServiceIDAttribute(a).ID;
FServices.AddOrSetValue(id, aService);
break;
end;
finally
ctx.Free();
end;
end;
さて、エンドサービスについて。たとえば UserManager ユニット:
unit UserManager;
interface
uses AppServices;
const
SID_UserManager : TGUID = '{D94C9E3A-E645-4749-AB15-02631F21EC4E}';
type
[ServiceID('{D94C9E3A-E645-4749-AB15-02631F21EC4E}')]
TUserManager = class(TCustomAppService)
strict private
FActiveUserName: string;
public
property ActiveUserName: string read FActiveUserName;
end;
implementation
initialization
TAppServices.RegisterService(TUserManager.Create());
end.
これで、コードをテストできます。
procedure TestApp();
var uMgr :TUserManager;
dbMgr : TDBmanager;
begin
dbMgr := TAppServices.QueryService(SID_DBManager) as TDBManager;
if dbMgr.Connected then
writeln('connected!')
else writeln('not connected');
uMgr := TAppServices.QueryService(SID_UserManager) as TUserManager;
writeln('Active user: ', uMgr.ActiveUserName);
end;
summary:
TAppServices
アプリ内の任意のサービスへのアクセスを提供するメイン オブジェクトです。エンドサービスについて何も知らないため、依存関係はありません。必要に応じて実装を変更できます。必要な数の TCustomAppService クラスの子孫を持つことができます。アプリケーションに新しいサービスを追加する場合、TAppServices
クラス インターフェイスや実装を変更しないでください。