程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> Delphi >> DesignPattern之SimpleFactory

DesignPattern之SimpleFactory

編輯:Delphi
unit Unit2;

  interface

  uses
    Windows, Messages, SysUtils, Variants, Classes, Controls,
    Dialogs, ExtCtrls, ShellAPI, AppEvnts, Forms;
  type
    IFruitInterface = interface
      ['{D4557157-5241-4116-AA1E-87F86A884EA9}']
      procedure grow();
      procedure harvest();
      procedure plant();
    end;

  type
    TApple = class(TComponent, IFruitInterface)
    private
      treeAge: Integer;
    public
      procedure grow();
      procedure harvest();
      procedure plant();
    end;

    TStrwaBerry = class(TComponent, IFruitInterface)
    private
      treeAge: Integer;
    public
      procedure grow();
      procedure harvest();
      procedure plant();
    end;
    TGrape = class(TComponent, IFruitInterface)
    private
      treeAge: Integer;
    public
      procedure grow();
      procedure harvest();
      procedure plant();
    end;

    TFruitGarden = class
    public
      class function GetFruit(const strFruit: string): IFruitInterface;
    end;

  

  implementation
  //{$R *.dfm}
  procedure TApple.grow();
  begin
    showmessage('Apple grow');
  end;

  procedure TApple.harvest();
  begin
    showmessage('Apple harvest');
  end;

  procedure TApple.plant();
  begin
    showmessage('Apple plant');
  end;

  procedure TStrwaBerry.grow();
  begin
    showmessage('StrwaBerry plant');
  end;

  procedure TStrwaBerry.harvest();
  begin
    showmessage('StrwaBerry plant');
  end;

  procedure TStrwaBerry.plant();
  begin
    showmessage('StrwaBerry plant');
  end;

  procedure TGrape.grow();
  begin
    showmessage('Grape plant');
  end;

  procedure TGrape.harvest();
  begin
    showmessage('Grape plant');
  end;

  procedure TGrape.plant();
  begin
    showmessage('Grape plant');
  end;

  class function TFruitGarden.GetFruit(const strFruit: string): IFruitInterface;
  begin
    if strFruit = 'Apple' then
      Result := TApple.create(nil)
    else if strFruit = 'StrawBerry' then
      Result := TStrwaBerry.create(nil)
    else if strFruit = 'Grape' then
      Result := TGrape.create(nil)
    else
      raise Exception.Create('Cannot create ' + strFruit);
  end;

  end.
  

  //test

    AFruitGarden: TFruitGarden;
    AFruit: IFruitInterface;
  begin

    AFruitGarden := TFruitGarden.Create();
    try
      AFruit := AFruitGarden.GetFruit(Edit1.Text);
      AFruit.grow();
    except on FruitError: Exception do
        ShowMessage(FruitError.Message);
    end;

    FreeAndNil(AFruitGarden);
  end;
  

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved