1.意图
定义一个用于创建对象的接口,让子类决定实例化哪个类,Factory Method 使一个类的实例化延迟到其子类
2.例子
假设现在有一个对话框让你打开一个文件,可以是Word文档也可以是Excel文档,函数如下
function OpenDocument: TDocument;
由于应用程序依赖于抽象的Document类,所以我们不得不写这样的代码
if bIsWordDocument then
begin
Result := TWordDocument.Create;
//对WordDocument进行一些处理
...
end
else if bIsExcelDocument then
begin
Result := TExcelDocument.Create
//对ExcelDocument进行一些处理
end
...
begin
Result := TWordDocument.Create;
//对WordDocument进行一些处理
...
end
else if bIsExcelDocument then
begin
Result := TExcelDocument.Create
//对ExcelDocument进行一些处理
end
...
通过工厂方法,我们定义了创建Document类的接口,所以就把类的创建的代码转移到了另一个类中
Result := TWordDocumentFactory.GetInstance();
而抽象类 TDocumentFactory 只需要定义一个GetInstance()接口,他的子类负责具体实例化具体的对象。
参数化工厂:参数化工厂用的比较多一点
举例
TProductFactory = class(TObject)
public
class function GetInstance(ProductType: Integer): TAbstractProduct;
end; class function GetInstance(ProductType: Integer): TAbstractProduct;
begin
if ProductType = 1 then
Result := TProductA.Create
else
Result := TProductB.Create;
end;
public
class function GetInstance(ProductType: Integer): TAbstractProduct;
end; class function GetInstance(ProductType: Integer): TAbstractProduct;
begin
if ProductType = 1 then
Result := TProductA.Create
else
Result := TProductB.Create;
end;
这样,实际创建对象的类由TProductFactory来负责,并且转移到了实现的代码中,在接口定义部分(Delphi 的 interface 部分) 就不需要知道具体对象的类了。