工厂模式,初始化参数

时间:2016-01-09 14:40:34

标签: delphi delphi-xe2 factory factory-pattern

我正在阅读Hodges的书“Delphi中的更多编码”,关于工厂模式的部分。我想出了一个问题。我需要为TBaseGateway类的每个后代实现Init过程。问题是我不知道如何传递正确的记录类型。有什么好的解决方案吗?

unit Unit2;

interface

uses
  Generics.Collections, System.SysUtils, System.Classes, Dialogs;

type
  TGatewayTpe = (gtSwedbank, gtDNB);

type
  IGateway = interface
    ['{07472665-54F5-4868-B4A7-D68134B9770B}']
    procedure Send(const AFilesToSend: TStringList);
  end;

type
  TBaseGateway = class(TAggregatedObject, IGateway)
  public
    procedure Send(const AFilesToSend: TStringList); virtual; abstract;
  end;

type
  TSwedbankGateway = class(TBaseGateway)
  public
    // procedure Init(const ASwedbanRecord: TSwedBankRecord);
    procedure Send(const AFilesToSend: TStringList); override;
  end;

type
  TDNBGateway = class(TBaseGateway)
  public
    // procedure Init(const ADNBRecord: TDNBRecord);
    procedure Send(const AFilesToSend: TStringList); override;
  end;

type
  TGatewayFunction = reference to function: TBaseGateway;

type
  TGatewayTypeAndFunction = record
    GatewayType: TGatewayTpe;
    GatewayFunction: TGatewayFunction;
  end;

type
  TGatewayFactory = class
  strict private
    class var FGatewayTypeAndFunctionList: TList<TGatewayTypeAndFunction>;
  public
    class constructor Create;
    class destructor Destroy;
    class procedure AddGateway(const AGatewayType: TGatewayTpe;
      const AGatewayFunction: TGatewayFunction);
  end;

implementation

class procedure TGatewayFactory.AddGateway(const AGatewayType: TGatewayTpe;
  const AGatewayFunction: TGatewayFunction);

var
  _GatewayTypeAndFunction: TGatewayTypeAndFunction;
begin
  _GatewayTypeAndFunction.GatewayType := AGatewayType;
  _GatewayTypeAndFunction.GatewayFunction := AGatewayFunction;

  FGatewayTypeAndFunctionList.Add(_GatewayTypeAndFunction);
end;

class constructor TGatewayFactory.Create;
begin
  FGatewayTypeAndFunctionList := TList<TGatewayTypeAndFunction>.Create;
end;

class destructor TGatewayFactory.Destroy;
begin
  FreeAndNil(FGatewayTypeAndFunctionList);
end;

procedure TSwedbankGateway.Send(const AFilesToSend: TStringList);
begin
  ShowMessage(Self.ClassName);
end;

procedure TDNBGateway.Send(const AFilesToSend: TStringList);
begin
  ShowMessage(Self.ClassName);
end;

initialization

TGatewayFactory.AddGateway(gtDNB,
 function: TBaseGateway
  begin
    Result := TDNBGateway.Create(nil);
  end);

TGatewayFactory.AddGateway(gtSwedbank,
  function: TBaseGateway
  begin
    Result := TSwedbankGateway.Create(nil);
  end);

end.

0 个答案:

没有答案