打印本文 打印本文 关闭窗口 关闭窗口
用 Delphi 学设计模式(一) 之 简单工厂篇 (原创)
作者:武汉SEO闵涛  文章来源:敏韬网  点击数2432  更新时间:2009/4/23 18:27:20  文章录入:mintao  责任编辑:mintao
>

{ ********** TApple ********** }

function TApple.Grow: string;
begin
  result:=''''苹果正在生长......'''';
end;

function TApple.Harvest: string;
begin
  result:=''''苹果可以收获了......'''';
end;

function TApple.Plant: string;
begin
  result:=''''苹果已经种好了......'''';
end;

{ ********** TStrawberry ********** }

function TStrawberry.Grow: string;
begin
  result:=''''草莓正在生长......'''';
end;

function TStrawberry.Harvest: string;
begin
  result:=''''草莓可以收获了......'''';
end;

function TStrawberry.Plant: string;
begin
  result:=''''草莓已经种好了......'''';
end;

{ ********** TFruitGardener ********** }

class function TFruitGardener.Factory(whichFruit:string): IFruit;
begin
  //精髓就是这条语句了 result:= TApple.Create()
  //不明白赶紧去复习复习什么是多态性
  if(LowerCase(whichFruit)=''''apple'''')then result:=TApple.Create()
  else if(LowerCase(whichFruit)=''''grape'''')then result:=TGrape.Create()
  else if(LowerCase(whichFruit)=''''strawberry'''')then result:=TStrawberry.Create()
  else Raise NoThisFruitException.Create(''''这种水果还没有被种植!'''');
end;

end.

窗体界面:
//MainForm.pas 窗体文件,这里说明怎样使用简单工厂

unit MainForm;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs,SimpleFactory, StdCtrls;

type
  TForm1 = class(TForm)
    RadioButton1: TRadioButton;
    RadioButton2: TRadioButton;
    RadioButton3: TRadioButton;
    RadioButton4: TRadioButton;
    procedure RadioButton1Click(Sender: TObject);
    procedure RadioButton2Click(Sender: TObject);
    procedure RadioButton3Click(Sender: TObject);
    procedure RadioButton4Click(Sender: TObject);
  public
    procedure Produce(fruitName:string);
  end;
  
var
  Form1: TForm1;

implementation

{ ********** TForm1 ********** }

//这就是生产过程
//IFruit 类型的临时变量 f 自己知道种的是哪种水果,有趣吧
//想要什么尽管来种,果园大丰收啦!
procedure TForm1.Produce(fruitName:string);
var
  f: IFruit;
begin
  try
    f:=TFruitGardener.Factory(fruitName);
    ShowMessage(f.Plant());
    ShowMessage(f.Grow());
    ShowMessage(f.Harvest());
  except
    on e:NoThisFruitException do  Messagedlg(e.Message,mtInformation,[mbOK],0);
  end;
end;

{$R *.dfm}


procedure TForm1.RadioButton1Click(Sender: TObject);
begin
  Produce(''''apple''''

上一页  [1] [2] [3]  下一页

打印本文 打印本文 关闭窗口 关闭窗口