工厂类

//水果类,它是一个抽象产品
TFruit = Class(TObject)
...
end;
//
苹果类,水果类的具体化
TApple = class(TFruit)
...
end;

function Factory(): TFruit;
var
    f:TFruit;
begin
  //
精髓就是这条语句了,明明创建了TApple对象,
  //
却将他赋值给TFruit类型的变量
  //
其实这样做好处大大的,后面就体会到了
  f:=TApple.Create();
  result:=f;
end

//------------------------------------------------------------------------------------------------type
  //
水果类,它是一个抽象产品
  //
仅仅声明了所有对象共有的接口,并不实现他们
  IFruit = interface(IInterface)
    function Grow: string; //
生长
    function Harvest: string; //
收获
    function Plant: string;//
耕作
  end;

  //
葡萄类,水果类的具体化
  TGrape = class(TInterfacedObject, IFruit)
    function Grow: string;
    function Harvest: string;
    function Plant: string;
  end;

  //
苹果类,水果类的具体化
  TApple = class(TInterfacedObject, IFruit)
    function Grow: string;
    function Harvest: string;
    function Plant: string;
  end;

  //
草莓类,水果类的具体化
  TStrawberry = class(TInterfacedObject, IFruit)
    function Grow: string;
    function Harvest: string;
    function Plant: string;
  end;
 
  //
果园类,它就是工厂类,负责给出三种水果的实例
  TFruitGardener = class(TObject)
  public
    //1
、注意 class 关键字,它定义工厂方法 Factory 是一个静态函数,可以直接使用
    //2
、注意返回值,他返回的是最抽象的产品 IFruit 水果类接口
    //3
、注意他有一个参数,来告诉工厂创建哪一种水果
    class function Factory(whichFruit:string): IFruit;
  end;


原文地址:https://www.cnblogs.com/luckForever/p/7255005.html