Abstract Factory 提供一个创建一系列相关或相互依赖对象的接口,而无需指定他们具体的类.
生成代码如下
unit unit1;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs;
type
TAbstractProductA
=
class
(TObject)
end;
TAbstractProductB
=
class
(TObject)
end;
TProductB2
=
class
(TAbstractProductB)
end;
TProductB1
=
class
(TAbstractProductB)
end;
TProductA2
=
class
(TAbstractProductA)
end;
TProductA1
=
class
(TAbstractProductA)
end;
TAbstractFactory
=
class
(TObject)
public
function CreateProductA: TAbstractProductA;
virtual
;
abstract
;
function CreateProductB: TAbstractProductB;
virtual
;
abstract
;
end;
TConcreteFactoryFactory
=
class
(TObject)
public
class
function GetInstance(ProductType: integer): TAbstractFactory;
end;
TConcreteFactory2
=
class
(TAbstractFactory)
public
function CreateProductA: TAbstractProductA;
override
;
function CreateProductB: TAbstractProductB;
override
;
end;
TConcreteFactory1
=
class
(TAbstractFactory)
public
function CreateProductA: TAbstractProductA;
override
;
function CreateProductB: TAbstractProductB;
override
;
end;
implementation
{
***************************
TConcreteFactoryFactory
****************************
}
class
function TConcreteFactoryFactory.GetInstance(ProductType: integer):
TAbstractFactory;
begin
if
ProductType
=
1
then
Result :
=
TConcreteFactory1.Create
else
Result :
=
TConcreteFactory2.Create;
end;
{
******************************
TConcreteFactory2
*******************************
}
function TConcreteFactory2.CreateProductA: TAbstractProductA;
begin
Result :
=
TProductA2.Create;
end;
function TConcreteFactory2.CreateProductB: TAbstractProductB;
begin
Result :
=
TProductB2.Create;
end;
{
******************************
TConcreteFactory1
*******************************
}
function TConcreteFactory1.CreateProductA: TAbstractProductA;
begin
Result :
=
TProductA1.Create;
end;
function TConcreteFactory1.CreateProductB: TAbstractProductB;
begin
Result :
=
TProductB1.Create;
end;
end.