Delphi Abstract Factory(抽象工厂)

抽象工厂(Abstract Factory)模式也叫工具箱,它提供一个用于构建一群相关或相互依赖的对象,而无需指定他们的具体类。

 

unit NewPas;

interface

uses
  SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs;

type
  TCPU 
= class(TObject)
  
end;

  TAMD3400 
= class(TCPU)
  
end;

  TIntelCPU 
= class(TCPU)
  
end;

  TAMDDoubleCore 
= class(TCPU)
  
end;

  TIntelDoubleCore 
= class(TCPU)
  
end;

  THardDisk 
= class(TObject)
  
end;

  TSATAHardDisk 
= class(THardDisk)
  
end;

  TIDEHardDisk 
= class(THardDisk)
  
end;

  TNotebookIDEHardDisk 
= class(THardDisk)
  
end;

  TNotebookSATAHardDisk 
= class(THardDisk)
  
end;

  IComputerFactory 
= interface(IInterface)
    [
'{0FBF5ADD-F28E-45E5-AC22-D76FE9A2FFB3}']
    function CreateCPU: TCPU;
    
function CreateHardDisk: THardDisk;
  
end;

  TDellNotebookComputerFactory 
= class(TInterfacedObject, IComputerFactory)
  
public
    
function CreateCPU: TCPU;
    
function CreateHardDisk: THardDisk;
  
end;

  TLegendPCComputerFactory 
= class(TInterfacedObject, IComputerFactory)
  
public
    
function CreateCPU: TCPU;
    
function CreateHardDisk: THardDisk;
  
end;

  TComputer 
= class(TInterfacedObject)
  
private
    FCPU: TCPU;
    FHardDisk: THardDisk;
  
public
    constructor Create(ComputerFactory: IComputerFactory);
    
property CPU: TCPU read FCPU write FCPU;
    
property HardDisk: THardDisk read FHardDisk write FHardDisk;
  
end;

implementation


{ TComputer }

constructor TComputer.Create(ComputerFactory: IComputerFactory);
begin
  FCPU :
= ComputerFactory.CreateCPU;
  FHardDisk :
= ComputerFactory.CreateHardDisk;
end;

{ TDellNotebookComputerFactory }

function TDellNotebookComputerFactory.CreateCPU: TCPU;
begin
  Result :
= TIntelDoubleCore.Create;
end;

function TDellNotebookComputerFactory.CreateHardDisk: THardDisk;
begin
  Result :
= TNotebookSATAHardDisk.Create;
end;

{ TLegendPCComputerFactory }

function TLegendPCComputerFactory.CreateCPU: TCPU;
begin
  Result :
= TAMD3400.Create;
end;

function TLegendPCComputerFactory.CreateHardDisk: THardDisk;
begin
  Result :
= TIDEHardDisk.Create;
end;

end.

 

我们不需要为了Dell GX 620 声明一个非常具体的类

 

TDellGx620 = class(TComputer)

CPU: TIntel(R)
2.0G;

Memory: TDDR512;

...

end;

 

而是说由抽象工厂TDellGx620Factory来构建TComputer具体的部件,这样可以很好的避免类爆炸的问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值