unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TVisitableBase =
class;
TVisitor =
class(TPersistent)
public
constructor Create;
procedure Visit(element: TVisitableBase);
virtual;
end;
TVisitableBase =
class(TPersistent)
private
FCaption:
String;
protected
public
constructor Create(caption:
String);
procedure AcceptVisitor(visitor: TVisitor);
virtual;
property Caption:
String read FCaption
write FCaption;
end;
TVisitableDerived =
class(TVisitableBase)
private
FCount: Integer;
public
constructor Create(caption:
String; Count: Integer);
destructor Destroy;
override;
property Caption;
property Count: Integer
read FCount
write FCount;
end;
TVisitorDerived =
class(TVisitor)
public
constructor Create;
procedure Visit(element: TVisitableDerived);
overload;
end;
TForm1 =
class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private-Deklarationen }
public
{ Public-Deklarationen }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TVisitableBase }
procedure TVisitableBase.AcceptVisitor(visitor: TVisitor);
begin
if (Assigned(visitor))
then
visitor.Visit(Self);
end;
constructor TVisitableBase.Create(caption:
String);
begin
inherited Create;
FCaption := caption;
end;
{ TVisitor }
constructor TVisitor.Create;
begin
inherited;
end;
procedure TVisitor.Visit(element: TVisitableBase);
begin
if (element
is TVisitableDerived)
then
ShowMessage('
caption: ' + element.Caption + '
; count: ' + IntToStr(TVisitableDerived(element).Count))
else
raise Exception.Create('
Fehler: Base');
end;
{ TVisitableDerived }
constructor TVisitableDerived.Create(caption:
String; Count: Integer);
begin
inherited Create(caption);
FCount := count;
end;
destructor TVisitableDerived.Destroy;
begin
inherited;
end;
{ TVisitorDerived }
constructor TVisitorDerived.Create;
begin
inherited Create;
end;
procedure TVisitorDerived.Visit(element: TVisitableDerived);
begin
raise Exception.Create('
Fehler: Derived');
end;
procedure TForm1.Button1Click(Sender: TObject);
var
visitor: TVisitorDerived;
element: TVisitableDerived;
begin
visitor := TVisitorDerived.Create;
element := TVisitableDerived.Create('
Test', 100);
try
element.AcceptVisitor(visitor);
finally
element.Free;
visitor.Free;
end;
end;
end.