CSDN博客

img cooleyesbaby

Delphi设计模式-Abstract Factory

发表于2001/11/16 17:04:00  734人阅读

  模式的描述可以参考[1],下面举一个Delphi中的例子。

  通常Delphi中的Form都是自动Create,也可以在Form中写代码来创建(通常是在主Form中)。下面以Abstract Factory来创建Form。

//unit AbstractF

    TAbstractFactory = class
  public
    function CreateForm : TForm;virtual;abstract;
  end;

//unit ConcreteFA

  TConcreteFactoryA = class(TAbstractFactory)
  public
    function CreateForm : TForm; override;
  end;

{ TConcreteFactoryB }

function TConcreteFactoryA.CreateForm: TForm;
begin
  Result := TfrmFormA.Create(Application);
  Result.ShowModal;
end;

//unit ConcreteFB

  TConcreteFactoryB = class(TAbstractFactory)
  public
    function CreateForm : TForm; override;
  end;

{ TConcreteFactoryB }

function TConcreteFactoryB.CreateForm: TForm;
begin
  Result := TfrmFormB.Create(Application);
  Result.ShowModal;
end;

//主Form

unit MainFrm;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, AbstractF;

type
  TfrmMain = class(TForm)
    btnConcreteA: TButton;
    btnContreteB: TButton;
    procedure btnConcreteAClick(Sender: TObject);
    procedure btnContreteBClick(Sender: TObject);
  private
    { Private declarations }
    FAbstractFactory: TAbstractFactory;
  public
    { Public declarations }
  end;

var
  frmMain: TfrmMain;

implementation

uses ConcreteFA, ConcreteFB;

{$R *.dfm}

procedure TfrmMain.btnConcreteAClick(Sender: TObject);
begin
  FAbstractFactory:= TConcreteFactoryA.Create;
  FAbstractFactory.CreateForm;
  FAbstractFactory.Free;
end;

procedure TfrmMain.btnContreteBClick(Sender: TObject);
begin
  FAbstractFactory:= TConcreteFactoryB.Create;
  FAbstractFactory.CreateForm;
  FAbstractFactory.Free;
end;

end.

[参考资料]

1.《设计模式-可复用面向对象软件的基础》

阅读全文
0 0

相关文章推荐

img
取 消
img