DesignPattern之FactoryMethod

[入库:2005年8月18日] [更新:2007年3月24日]

本文简介:选择自 xiaoxiaoxuesheng 的 blog

unit factory;

interface
uses windows, messages, sysutils, controls, product;

type
  ifactoryinterface = interface
    function factory(): iproductinterface;
  end;

  tfactory1 = class(tcontrol, ifactoryinterface)
  public
    function factory(): iproductinterface;
  end;

  tfactory2 = class(tcontrol, ifactoryinterface)
  public
    function factory(): iproductinterface;
  end;

implementation

function tfactory1.factory(): iproductinterface;
var
  aproduct: tproduct1;
begin
  aproduct := tproduct1.create(nil);
  result := aproduct.createproduct();
end;

function tfactory2.factory(): iproductinterface;
var
  aproduct: tproduct2;
begin
  aproduct := tproduct2.create(nil);
  result := aproduct.createproduct();
end;

end.

unit product;

interface
uses windows, messages, sysutils, controls, dialogs;

type
  iproductinterface = interface
    function createproduct(): iproductinterface;
  end;

  tproduct1 = class(tcontrol, iproductinterface)
  public
    function createproduct(): iproductinterface;
  end;
  tproduct2 = class(tcontrol, iproductinterface)
  public
    function createproduct(): iproductinterface;
  end;

implementation

function tproduct1.createproduct(): iproductinterface;
begin
  result := self;
  showmessage('product1 created');
end;

function tproduct2.createproduct(): iproductinterface;
begin
  result := self;
  showmessage('product2 created');
end;


end.

//测试

procedure tform1.button1click(sender: tobject);
var
  afactory: tfactory1;
begin
  afactory := tfactory1.create(self);
  afactory.factory;
  freeandnil(afactory);
end;

procedure tform1.button2click(sender: tobject);
var
  afactory: tfactory2;
begin
  afactory := tfactory2.create(self);
  afactory.factory;
  freeandnil(afactory);
end;

本文关键:DesignPattern之FactoryMethod
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top