一、简单工厂模式(simple factory method)

抽象产品:如抽象类水果(Fruit)。

具体产品:如从Fruit继承下来的苹果、葡萄等。

工厂:负责生产各种水果。

unit FactoryMethodUnit;

interface
type
  TFruitID = (Grape,Apple);
  TFruit = class //抽象接口
  public
    constructor Create; virtual;
  end;
  TGrape= class(Fruit)//具体类
    constructor Create; override;
  end;
  TApple= class(Fruit)//具体类
    constructor Create; override;
  end;

  TCreator = class  //工厂
  public
    constructor Create; virtual;
    function CreateProduct(FruitID : TFruitID): TFruit; virtual; 
  end;

  TMyCreator = class(TCreator)
    constructor Create; override;
   function CreateProduct(FruitID : TFruitID): TFruit; override; //
  end;

implementation

function TCreator.CreateProduct(FruitID : TFruitID ): TFruit;
var
  aProduct: TFruit;
begin
  aProduct := nil;
  if FruitID = Grape then
    aProduct := TGrape.Create;
  if FruitID = Apple then
    aProduct := TApple.Create;
  Result := aProduct;
end;


constructor TGrape.Create;
begin
//......
end;

constructor TApple.Create;
begin
//......
end;

constructor TCreator.Create;
begin
//......
end;

constructor TMyCreator.Create;
begin
//......
end;

function TMyCreator.CreateProduct(FruitID : TFruitID ): TFruit;
var
  aProduct: TFruit;
  aCreator: TCreator;
begin

  aProduct := nil;
  if FruitID = Grape then
    aProduct := TGrape.Create;
  if FruitID = Apple then
    aProduct := TApple.Create;

  if aProduct = nil then
  begin
    aCreator := Tcreator.Create;
    aProduct := aCreator.CreateProduct(FruitID);
  end;
  Result := aProduct;
end;

 

end.

在简单工厂模式中,一个工厂类处于对产品类实例化的中心位置上,它知道每一个产
品,它决定哪一个产品类应当被实例化。这个模式的优点是允许客户端相对独立于产品创
建的过程,并且在系统引入新产品的时候无需修改客户端,也就是说,它在某种程度上支
持“开-闭”原则。这个模式的缺点是对“开-闭”原则的支持不够,因为如果有新的产品加入到系统中去,就需要修改工厂类,将必要的逻辑加入到工厂类中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值