工厂方法(Factory Method)模式,又称虚构造子(Virtual Constructor)模式或多态工厂模式。工厂模式定义创建对象的借口,并由派生类决定哪一个类来创建对象。也就是说,工厂方法将创建对象的责任委托给派生类。这是因为基类并不知道要创建的对象是哪一个类的实例,所以将创建对象的责任委托给派生类,或者将实际创建工作延迟到派生类中完成。
TCPU
=
class
(TObject)
end ;
TAMDCPU = class (TCPU)
end ;
TIntelCPU = class (TCPU)
end ;
TCPUFactory = class (TObject)
public
// 将对象的创建转移到派生类
function CreateCPU: TCPU; virtual; abstract;
end ;
TAMDCPUFactory = class (TCPUFactory)
public
function CreateCPU; TCPU; override;
end ;
TIntelCPUFactory = class (TCPUFactory)
public
function CreateCPU: TCPU; override
end ;
end ;
TAMDCPU = class (TCPU)
end ;
TIntelCPU = class (TCPU)
end ;
TCPUFactory = class (TObject)
public
// 将对象的创建转移到派生类
function CreateCPU: TCPU; virtual; abstract;
end ;
TAMDCPUFactory = class (TCPUFactory)
public
function CreateCPU; TCPU; override;
end ;
TIntelCPUFactory = class (TCPUFactory)
public
function CreateCPU: TCPU; override
end ;
看一下具体的实现
function
TAMDCPUFactory.CreateCPU: TCPU;
begin
Result : = TAMDCPU.Create;
end ;
begin
Result : = TAMDCPU.Create;
end ;
再来看客户端,在未使用工厂方法前
TComputer
=
class
(TObject)
private
FAMDCPU: TAMDCPU;
public
end ;
FAMDCPU : = TAMDCPU.Create;
private
FAMDCPU: TAMDCPU;
public
end ;
FAMDCPU : = TAMDCPU.Create;
使用工厂方法以后
TComputer
=
class
(TObject)
private
FAMDCPU: TCPU;
AMDCPUFactory; TFactory;
public
end ;
FAMDCPU : = AMDCPUFactory.CreateCPU;
private
FAMDCPU: TCPU;
AMDCPUFactory; TFactory;
public
end ;
FAMDCPU : = AMDCPUFactory.CreateCPU;
这个时候,TComputer类中的FAMDCPU声明为了一个TCPU而不是具体的CPU.
再来看参数化工厂
TCPUFactory
=
class
(TObject)
public
function CreateCPU(CPUType: TCPUType): TCPU;
end ;
function TCPUFactory.CreateCPU(CPUType: TCPUType): TCPU;
begin
case CPUType of
tpAMD: Result : = TAMDCPU.Create;
tpIntel: Result : = TIntelCPU.Create;
end ;
end ;
public
function CreateCPU(CPUType: TCPUType): TCPU;
end ;
function TCPUFactory.CreateCPU(CPUType: TCPUType): TCPU;
begin
case CPUType of
tpAMD: Result : = TAMDCPU.Create;
tpIntel: Result : = TIntelCPU.Create;
end ;
end ;
参数化工厂把不同对象的创建以一个统一的接口实现。