- unit uFactoryMethod;
- interface
- uses Classes,Windows,Messages,Dialogs;
- type
- TMobile = class
- public
- procedure Call();virtual;abstract;
- end;
- TNokia = class(TMobile)
- public
- constructor Create();
- procedure Call();override;
- end;
- TMotorola = class(TMobile)
- public
- constructor Create;
- procedure Call();override;
- end;
- TMobileFactory = class
- public
- function produceMobile():TMobile;virtual; abstract;
- end;
- TMotorolaFactory = class(TMobileFactory)
- public
- function produceMobile():TMobile;override;
- end;
- TNokiaFactory = class(TMobileFactory)
- private
- public
- function produceMobile():TMobile;override;
- end;
- implementation
- { TNokia }
- procedure TNokia.Call;
- begin
- inherited;
- ShowMessage('a call of Nokia');
- end;
- constructor TNokia.Create;
- begin
- end;
- { TMotorola }
- procedure TMotorola.Call;
- begin
- inherited;
- ShowMessage('a call of motorola');
- end;
- constructor TMotorola.Create;
- begin
- end;
- { TMotorolaFactory }
- function TMotorolaFactory.produceMobile: TMobile;
- var
- Motorola:TMotorola;
- begin
- Motorola:=TMotorola.Create;
- Result:=Motorola;
- end;
- { TNokiaFactory }
- function TNokiaFactory.produceMobile: TMobile;
- var
- Nokia:TNokia;
- begin
- Nokia:=TNokia.Create;
- Result:=Nokia;
- end;
- end.
- //=============================================================================
- //测试工厂模式
- //============================================================================
- unit Unit1;
- interface
- uses
- Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
- Dialogs, StdCtrls;
- type
- TForm1 = class(TForm)
- Button1: TButton;
- Button2: TButton;
- procedure Button1Click(Sender: TObject);
- procedure Button2Click(Sender: TObject);
- private
- { Private declarations }
- public
- { Public declarations }
- end;
- var
- Form1: TForm1;
- implementation
- uses uFactoryMethod;
- {$R *.dfm}
- procedure TForm1.Button1Click(Sender: TObject);
- var
- mbf:TMobileFactory;
- mb:TMobile;
- begin
- mbf:=TMotorolaFactory.Create;
- mb:=mbf.produceMobile;
- mb.Call;
- end;
- procedure TForm1.Button2Click(Sender: TObject);
- var
- mbf:TMobileFactory;
- mb:TMobile;
- begin
- mbf:=TNokiaFactory.Create;
- mb:=mbf.produceMobile;
- mb.Call;
- end;
- end.