工厂模式,有工厂就有产品,工厂里就是加工产品的,这个模式有以下参与者:
1.抽象产品,对象产品的对像接口或抽象层。
2.具体产口,实现抽象产品的接口。
3.抽象工厂,工厂的方法,方法用于反回产品对象。可以用抽象类或接口定义
4.具体工厂,实现抽象工厂接口的具体类
1 unit Unit1; 2 3 interface 4 5 uses 6 Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, 7 System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, 8 Vcl.StdCtrls; 9 10 type 11 TProcedure = class(TObject)//产品抽象类 12 public 13 procedure ShowCarName; virtual; abstract; 14 end; 15 16 TProcedureNissan = class(TProcedure) //产品具体类 17 public 18 procedure ShowCarName; override; 19 end; 20 21 TProcedureToyota = class(TProcedure) //产品具体类 22 public 23 procedure ShowCarName; override; 24 end; 25 26 TFactoryInterface = class(TObject) //工厂抽象类 27 public 28 function CreateProcedure: TProcedure; virtual; abstract;//返回产品 29 end; 30 31 TFactoryNissan = class(TFactoryInterface) //工厂具体类 32 public 33 function CreateProcedure: TProcedure; override; 34 end; 35 36 TFactoryToyota = class(TFactoryInterface) //工厂具体类 37 public 38 function CreateProcedure: TProcedure; override; 39 end; 40 41 TForm1 = class(TForm) 42 btn1: TButton; 43 btn2: TButton; 44 procedure FormCreate(Sender: TObject); 45 procedure btn1Click(Sender: TObject); 46 procedure btn2Click(Sender: TObject); 47 private 48 { Private declarations } 49 public 50 { Public declarations } 51 end; 52 53 var 54 Form4: TForm4; 55 56 implementation 57 58 {$R *.dfm} 59 60 procedure TForm4.btn1Click(Sender: TObject); 61 var 62 _CarFactory: TFactoryInterface; 63 _CarClass: TProcedure; 64 begin 65 _CarFactory := TFactoryNissan.Create; 66 _CarClass := _CarFactory.CreateProcedure; 67 _CarClass.ShowCarName; 68 _CarClass.Free; 69 _CarFactory.Free; 70 end; 71 72 procedure TForm4.btn2Click(Sender: TObject); 73 var 74 _CarFactory: TFactoryInterface; 75 _CarClass: TProcedure; 76 begin 77 _CarFactory := TFactoryToyota.Create; 78 _CarClass := _CarFactory.CreateProcedure; 79 _CarClass.ShowCarName; 80 _CarClass.Free; 81 _CarFactory.Free; 82 end; 83 84 procedure TForm4.FormCreate(Sender: TObject); 85 begin 86 87 end; 88 89 { TProcedureToyota } 90 91 procedure TProcedureToyota.ShowCarName; 92 begin 93 ShowMessage('这个是丰田汽车 TOYOTA'); 94 end; 95 96 { TProcedureNissan } 97 98 procedure TProcedureNissan.ShowCarName; 99 begin 100 ShowMessage('这个是日产汽车 NISSAN'); 101 end; 102 103 { TFactoryNissan } 104 105 function TFactoryNissan.CreateProcedure: TProcedure; 106 begin 107 Result := TProcedure(TProcedureNissan.Create); 108 end; 109 110 { TFactoryToyota } 111 112 function TFactoryToyota.CreateProcedure: TProcedure; 113 begin 114 Result := TProcedure(TProcedureToyota.Create); 115 end; 116 117 end.
总结,工厂模式一般用途返回一个对象,将产品和工厂进行分离后,各自进行抽象和多态。这个原型结构看似简单但在实际使用过程中却可以灵活运用。通过类中的工厂方法创建产品,可以系统在不修改具体的工厂角色的情况下引进新产品(扩展)。工
厂模式相当于给工厂派生一个挂钩以便提供对象的一个扩充版本。
这个思想也同样应当应用于具体项目的开发和实施当中,将具体业务逻辑和代码分离,以抽象接口方法实现,这样可以使ERP/MES/PDM等项目具有非常好的可扩展性和灵活性,并且不受开发平台和开发语言的限制,真正实现跨平台,提高IT产品的生命周期和生态圈。