示例:ClassBuilder
实现:
ClassBuilder是一个生成器,Class使用它为自己创建子类。在这个例子中,一个Class既是Director也是Product。
代码:
unit uClassBuilder;
interface
uses
SysUtils;
type
TClassBuilder = class;
TClass = class
public
procedure Construct(Builder: TClassBuilder);
end;
TClassBuilder = class
public
procedure BuildClass(AClass:TClass); virtual;
end;
TConcreteBuilder = class(TClassBuilder)
private
FClassInfo: string;
public
constructor Create;
//---
procedure BuildClass(AClass:TClass); override;
function GetResult: string;
end;
implementation
procedure TClassBuilder.BuildClass;
begin
end;
constructor TConcreteBuilder.Create;
begin
FClassInfo := '';
end;
procedure TConcreteBuilder.BuildClass(AClass:TClass);
begin
FClassInfo := format('%0:s1 = class(%0:s) end;',[AClass.ClassName]);
end;
function TConcreteBuilder.GetResult: string;
begin
Result := FClassInfo;
end;
procedure TClass.Construct(Builder: TClassBuilder);
begin
Builder.BuildClass(self);
end;
end.
procedure TForm1.Button1Click(Sender: TObject);
var
AClass: TClass;
Builder: TConcreteBuilder;
begin
AClass := TClass.Create;
Builder := TConcreteBuilder.Create;
//--
AClass.Construct(Builder);
showmessage(Builder.GetResult);
//---
Builder.Free;
AClass.Free;
end;