依然是java 與模式裡的例子,(Java 與模式 闫宏著) 以下是轉為Delphi的代碼,這次加了注釋:)
unit BuilderPattern;
interface
type
TProduct = class;
//抽像建造者 規范接口
TBuilder = class(TObject)
public
procedure builderpart1(); virtual; abstract;
procedure builderpart2(); virtual; abstract;
function returnProduct(): TProduct; virtual; abstract;
end;
//具體的創建者類,組件同他來創建,這樣客戶端不用知道具體的建造細節
TConcreteBuilder = class(TBuilder)
private
product: TProduct;
public
procedure builderpart1(); override;
procedure builderpart2(); override;
function returnProduct(): TProduct; override;
end;
//產品類
TProduct = class(TObject)
//
end;
//導演者角色,直接被客戶端使用
TDirector = class(TObject)
private
Builder: TBuilder;
public
procedure Initialize();
end;
implementation
{ TDirector }
procedure TDirector.Initialize;
begin
Builder := TConcreteBuilder.Create;
Builder.builderpart1();
Builder.builderpart2();
Builder.returnProduct;
end;
{ TConcreteBuilder }
procedure TConcreteBuilder.builderpart1;
begin
// your code
end;
procedure TConcreteBuilder.builderpart2;
begin
// your code
end;
function TConcreteBuilder.returnProduct: TProduct;
begin
Result := product;
end;