现在的位置: 首页 > 综合 > 正文

Delphi Abstract Factory(抽象工厂)

2018年04月07日 ⁄ 综合 ⁄ 共 2085字 ⁄ 字号 评论关闭

抽象工厂(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具体的部件,这样可以很好的避免类爆炸的问题。

抱歉!评论已关闭.