工厂模式,有工厂就有产品,工厂里就是加工产品的,这个模式有以下参与者:
1.抽象产品,对象产品的对像接口或抽象层。
2.具体产口,实现抽象产品的接口。
3.抽象工厂,工厂的方法,方法用于反回产品对象。可以用抽象类或接口定义
4.具体工厂,实现抽象工厂接口的具体类
unit Unit4;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls;
type
TProcedure = class(TObject)//产品抽象类
public
procedure ShowCarName; virtual; abstract;
end;
TProcedureNissan = class(TProcedure) //产品具体类
public
procedure ShowCarName; override;
end;
TProcedureToyota = class(TProcedure) //产品具体类
public
procedure ShowCarName; override;
end;
TFactoryInterface = class(TObject) //工厂抽象类
public
function CreateProcedure: TProcedure; virtual; abstract;//返回产品
end;
TFactoryNissan = class(TFactoryInterface) //工厂具体类
public
function CreateProcedure: TProcedure; override;
end;
TFactoryToyota = class(TFactoryInterface) //工厂具体类
public
function CreateProcedure: TProcedure; override;
end;
TForm4 = class(TForm)
btn1: TButton;
btn2: TButton;
procedure FormCreate(Sender: TObject);
procedure btn1Click(Sender: TObject);
procedure btn2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form4: TForm4;
implementation
{$R *.dfm}
procedure TForm4.btn1Click(Sender: TObject);
var
_CarFactory: TFactoryInterface;
_CarClass: TProcedure;
begin
_CarFactory := TFactoryNissan.Create;
_CarClass := _CarFactory.CreateProcedure;
_CarClass.ShowCarName;
_CarClass.Free;
_CarFactory.Free;
end;
procedure TForm4.btn2Click(Sender: TObject);
var
_CarFactory: TFactoryInterface;
_CarClass: TProcedure;
begin
_CarFactory := TFactoryToyota.Create;
_CarClass := _CarFactory.CreateProcedure;
_CarClass.ShowCarName;
_CarClass.Free;
_CarFactory.Free;
end;
procedure TForm4.FormCreate(Sender: TObject);
begin
end;
{ TProcedureToyota }
procedure TProcedureToyota.ShowCarName;
begin
ShowMessage('这个是丰田汽车 TOYOTA');
end;
{ TProcedureNissan }
procedure TProcedureNissan.ShowCarName;
begin
ShowMessage('这个是日产汽车 NISSAN');
end;
{ TFactoryNissan }
function TFactoryNissan.CreateProcedure: TProcedure;
begin
Result := TProcedure(TProcedureNissan.Create);
end;
{ TFactoryToyota }
function TFactoryToyota.CreateProcedure: TProcedure;
begin
Result := TProcedure(TProcedureToyota.Create);
end;
end.
总结,工厂模式一般用途返回一个对象,将产品和工厂进行分离后,各自进行抽象和多态。这个原型结构看似简单但在实际使用过程中却可以灵活运用。通过类中的工厂方法创建产品,可以系统在不修改具体的工厂角色的情况下引进新产品(扩展)。工
厂模式相当于给工厂派生一个挂钩以便提供对象的一个扩充版本。
来源:https://www.cnblogs.com/carcode/p/12514409.html