Паттерн строитель
Когда необходимо создать объект (TProduct) из разных блоков. Разные строители (TConcreteBuilder) могут использовать разные технологии.
Main
program Builder;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
uBuilder in 'uBuilder.pas';
var
b: TBuilder;
d: TDirector;
p: TProduct;
begin
try
b := TConcreteBuilder.Create();
d := TDirector.Create(b);
try
p := d.Construct();
Writeln('done');
Readln;
finally
b.Free();
d.Free();
p.Free();
end;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
Модуль uBuilder
unit uBuilder;
interface
uses
System.Generics.Collections, System.SysUtils;
type
TProduct = class
private
FParts: TObjectList<TObject>;
public
constructor Create();
destructor Destroy; override;
procedure Add(aPart: TObject);
end;
TBuilder = class
public
procedure BuldPartA(); virtual; abstract;
procedure BuldPartB(); virtual; abstract;
procedure BuldPartC(); virtual; abstract;
function GetProduct(): TProduct; virtual; abstract;
end;
TConcreteBuilder = class(TBuilder)
private
FProduct: TProduct;
public
constructor Create();
destructor Destroy; override;
procedure BuldPartA(); override;
procedure BuldPartB(); override;
procedure BuldPartC(); override;
function GetProduct(): TProduct; override;
end;
type
TDirector = class
private
FBuilder: TBuilder;
public
constructor Create(aBuilder: TBuilder);
destructor Destroy; override;
function Construct(): TProduct;
end;
implementation
{ TDirector }
function TDirector.Construct: TProduct;
begin
FBuilder.BuldPartA();
FBuilder.BuldPartB();
FBuilder.BuldPartC();
Result := FBuilder.GetProduct();
end;
constructor TDirector.Create(aBuilder: TBuilder);
begin
FBuilder := TConcreteBuilder.Create();
end;
destructor TDirector.Destroy;
begin
FBuilder.Free();
inherited;
end;
{ TProduct }
procedure TProduct.Add(aPart: TObject);
begin
FParts.Add(aPart);
end;
constructor TProduct.Create;
begin
FParts := TObjectList<TObject>.Create(true);
end;
destructor TProduct.Destroy;
begin
FParts.Free();
inherited;
end;
{ TConcreteBuilder }
procedure TConcreteBuilder.BuldPartA;
var
s: string;
begin
s := 'partA';
FProduct.Add(TObject(s));
end;
procedure TConcreteBuilder.BuldPartB;
var
s: string;
begin
s := 'partB';
FProduct.Add(TObject(s));
end;
procedure TConcreteBuilder.BuldPartC;
var
s: string;
begin
s := 'partC';
FProduct.Add(TObject(s));
end;
constructor TConcreteBuilder.Create;
begin
FProduct := TProduct.Create();
end;
destructor TConcreteBuilder.Destroy;
begin
FProduct.Free();
inherited;
end;
function TConcreteBuilder.GetProduct: TProduct;
begin
Result := FProduct;
end;
end.
2 Responses to DesignPatterns. Builder