模式的描述可以参考[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.《设计模式-可复用面向对象软件的基础》