什么是构造此通用对象创建的正确方法 [英] What is the correct way to structure this generic object creation

查看:85
本文介绍了什么是构造此通用对象创建的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

忽略了它使用Aurelius框架这一事实,这个问题更多地是关于我需要如何重新调整代码以使通用构造函数注入对这两种类型都起作用:
<字符串>

<TCustomConnection>
还要忽略子对象位于同一单元中的事实,我通常将它们放在单独的单元中,但这只会使在问题中发布更为容易.

Ignoring the fact that this uses the Aurelius Framework, this question is more about how I need to re-tweak the code to make the generic constructor injection work for both type:
< string >
and
< TCustomConnection >
Also ignore the fact that the child objects are in the same unit, I would generally put them in their own, but this just makes it easier to post in a question.

我正在尝试使用Factory Method模式来确定它在运行时应建立的连接类型,具体取决于我实例化的对象.目前,它正在硬编码它在创建时期望的链接类型.

I'm trying use the Factory Method pattern to determine what type of connection it should be making at runtime depending on what object I instantiate. At the moment it is hardcoding the type of link it is expecting on the create.

在该示例中,我想传递一个TModelDatabaseLink,但想在运行时确定它可以是哪种类型的数据库连接,或者数据库连接是否来自文件.是的,我知道我可以取消注释FFilename并仅使用它来保存文件名版本,但是我一直对学习更多内容感兴趣.

In the example I want to pass in a TModelDatabaseLink, but want to decide at run time what type of database connection it could be, or whether the database connection comes from a file. Yes I know I could uncomment FFilename and just use this to hold the file name version, but I am always interested in learning a bit more.

unit Model.Database.Connection;

interface

uses
  System.Classes,
  Data.DB,
  Aurelius.Drivers.Interfaces,
  Aurelius.Engine.DatabaseManager;

type
  TModelDatabaseLink<T> = class
  private
    //FFilename: string;
    FConnection: T;
    FOwnsConnection: boolean;
    OwnedComponent: TComponent;
  end;

  TModelDatabaseConnection = class abstract
  private
    FDatabaseLink: TModelDatabaseLink<TCustomConnection>;
    FDatabaseManager: TDatabaseManager;
    FConnection: IDBConnection;
    function CreateConnection: IDBConnection; virtual; abstract;
    procedure CreateDatabaseManager;
  public
    constructor Create(ADatabaseLink: TModelDatabaseLink<TCustomConnection>);
    destructor Destroy; override;

    property Connection: IDBConnection read FConnection;
  end;

  TSQLLiteConnection = class(TModelDatabaseConnection)
  private
    function CreateConnection: IDBConnection; override;
  end;

  TFireDacConnection = class(TModelDatabaseConnection)
  private
    function CreateConnection: IDBConnection; override;
  end;

implementation

uses
  System.SysUtils,

  Aurelius.Drivers.Base,
  Aurelius.Drivers.SQLite,
  Aurelius.Drivers.FireDac,

  FireDAC.Stan.Intf, FireDAC.Stan.Option,
  FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
  FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.VCLUI.Wait,
  FireDAC.Comp.Client;

{ TModelDatabaseConnection }

constructor TModelDatabaseConnection.Create(ADatabaseLink: TModelDatabaseLink<TCustomConnection>);
begin
  FDatabaseLink := ADatabaseLink;
  FConnection := CreateConnection;
  if Assigned(FConnection) then
    CreateDatabaseManager
  else
    raise Exception.Create('Failed to open database');
end;

procedure TModelDatabaseConnection.CreateDatabaseManager;
begin
  FDatabaseManager := TDatabaseManager.Create(FConnection);
end;

destructor TModelDatabaseConnection.Destroy;
begin
  FDatabaseManager.Free;
  FDatabaseLink.Free;
  inherited Destroy;
end;

{ TSQLLiteConnection }

function TSQLLiteConnection.CreateConnection: IDBConnection;
var
  LFilename: String;
  LAdapter: TSQLiteNativeConnectionAdapter;
begin
  //LFileName := FDatabaseLink.FConnection;                     << needs to be type string
  LAdapter := TSQLiteNativeConnectionAdapter.Create(LFilename);
  LAdapter.DisableForeignKeys;
  Result := LAdapter;
end;

{ TFireDacConnection }

function TFireDacConnection.CreateConnection: IDBConnection;
var
  LAdapter: TFireDacConnectionAdapter;
begin
  if Assigned(FDatabaseLink.OwnedComponent) then
    LAdapter := TFireDacConnectionAdapter.Create(FDatabaseLink.FConnection as TFDConnection, FDatabaseLink.OwnedComponent)
  else
    LAdapter := TFireDacConnectionAdapter.Create(FDatabaseLink.FConnection as TFDConnection, FDatabaseLink.FOwnsConnection);

  Result := LAdapter;
end;

end.

如果可能的话,我想做的另一件事是更改两个作品:

One other thing I would like to do if possible, is to change two creations:

LAdapter := TSQLiteNativeConnectionAdapter.Create(LFilename)

LAdapter := TFireDacConnectionAdapter.Create(FDatabaseLink.FConnection as TFDConnection, FDatabaseLink.OwnedComponent)

在父TModelDatabaseConnection中使用抽象的"GetAdapterClass"类型的函数,并在子级中声明适配器的类以执行以下操作:

to use an abstract "GetAdapterClass" type function in the parent TModelDatabaseConnection and just declare the class of adapter in the child to do something like:

LAdapter := GetAdapterClass.Create...

适配器声明的示例是

TFireDacConnectionAdapter = class(TDriverConnectionAdapter<TFDConnection>, IDBConnection)

推荐答案

在编写抽象层之前,我已经做到了这一点,以防万一我需要在应用程序中替换Aurelius.我认为处理您想要做的事情的最好方法是使用接口.

I have done this before when I wrote an abstract layer in case I need to replace Aurelius in my applications. I think the best way to deal with what you want to do is to use interfaces.

我在这里复制了部分代码并进行了调整:

I am copying here some parts of my code with adjustments:

  TServerType = (stLocal, stFireDac);

  IDatabase = interface
    function getDatabaseType: TServerType;
    property DatabaseType: TServerType read getDatabaseType;
  end;

  IAurelius = interface (IDatabase)
    ['{990BB776-2E70-4140-B118-BEFF61FDBDAF}']
    function getDatabaseConnection: IDBConnection;
    function getDatabaseManager: TDatabaseManager;
    property DatabaseConnection: IDBConnection read getDatabaseConnection;
    property DatabaseManager: TDatabaseManager read getDatabaseManager;
  end;

  IAureliusLocal = interface (IAurelius)
    ['{9F705CC4-6E3B-4706-B54A-F0649CED3A8D}']
    function getDatabasePath: string;
    property DatabasePath: string read getDatabasePath;
  end;

  IAureliusFireDac = interface (IAurelius)
    // I use this for a memory database but the logic is the same for FireDAC. You need to add the required properties 
  end;

  TAurelius = class (TInterfacedObject, IAurelius)
  private
    fServerType: TServerType;
    fDatabaseConnection: IDBConnection;
    fDatabaseManager: TDatabaseManager;
    function getDatabaseConnection: IDBConnection;
    function getDatabaseManager: TDatabaseManager;
  public
    constructor Create (const serverType: TServerType);
  end;

  TAureliusLocal = class (TAurelius, IAureliusLocal)
  private
    fDatabasePath: string;
    function getDatabasePath: string;
  public
    constructor Create (const databasePath: string);
  end;

  TAureliusFireDac = class (TAurelius, IAureliusFireDac)
  public 
    constructor Create (const aConnection: TFDConenction); <-- or whatever parameters you need here to initalise the FireDac connection
  end;

我将在此处跳过所有getXXX函数的代码.

I am going to skip the code for all the getXXX functions here.

构造函数是这些:

constructor TAurelius.Create(const serverType: TServerType);
begin
  inherited Create;
  fServerType:=serverType;
end;

constructor TAureliusLocal.Create (const databasePath: string);
const
  databaseFilename = 'test.sqlite';
begin
  inherited Create(stLocal);
  fDatabasePath:=Trim(databasePath);
   try
    fDatabaseConnection:=
    TSQLiteNativeConnectionAdapter.Create(
      TPath.Combine(fDatabasePath, databaseFilename));
   except
    raise Exception.Create('stLocal database can''t be created');
   end;
end;

constructor TAureliusFireDac.Create (const aConnection: TFDConenction);
begin
  inherited Create(stFireDac);
  // <-- here you initialise the connection like before but for FireDac
end;

现在,当您要创建Aurelius数据库时,可以使用以下功能:

Now, when you want to create an Aurelius database you use the following functions:

function createAureliusDatabase (const serverType: TServerType): IAurelius;
begin
  case serverType of
    stLocal: result:=TAureliusLocal.Create(path);
    stFireDac: result:=TAureliusFireDac.Create(....);
  end;
end;

...而您只是这样称呼它:

...and you simply call it like this:

var 
  currentDatabase: IAurelius;
begin
  currentDatabase:=createAureliusDatabase(stLocal,'c:\....');
end;

处理数据库创建的一种更好的方法是使用具有不同参数的重载函数或匿名方法来避免case-end分支.

A better way to deal with the creation of the database is to use overloaded functions with different parameters or anonymous methods to avoid the case-end branch.

这篇关于什么是构造此通用对象创建的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆