program Project2;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
type
TBase =
class abstract
protected
procedure InteractionTo( Dest: TBase );
virtual;
public
procedure InteractWith( Source: TBase );
virtual;
end;
TStrength =
class( TBase )
private
FValue: Integer;
public
function ToString:
string;
override;
property Value: Integer
read FValue
write FValue;
end;
TUpgrade =
class abstract( TBase )
private
FValue: Integer;
public
constructor Create( Value: Integer );
property Value: Integer
read FValue;
end;
TSomeUpgrade =
class( TUpgrade )
protected
procedure InteractionTo( Dest: TBase );
override;
end;
TSomeOtherUpgrade =
class( TUpgrade )
protected
procedure InteractionTo( Dest: TBase );
override;
end;
{ TBase }
procedure TBase.InteractionTo( Dest: TBase );
begin
raise Exception.Create( '
Cannot interact' );
end;
procedure TBase.InteractWith( Source: TBase );
begin
Source.InteractionTo( Self );
end;
{ TStrength }
function TStrength.ToString:
string;
begin
Result := Format( '
Strength = %d', [ FValue ] );
end;
{ TSomeUpgrade }
procedure TSomeUpgrade.InteractionTo( Dest: TBase );
begin
if Dest
is TStrength
then
begin
TStrength( Dest ).Value := TStrength( Dest ).Value + Self.Value;
Self.FValue := 0;
end
else
inherited;
end;
{ TSomeOtherUpgrade }
procedure TSomeOtherUpgrade.InteractionTo( Dest: TBase );
begin
if Dest
is TStrength
then
begin
TStrength( Dest ).Value := TStrength( Dest ).Value * Self.Value;
Self.FValue := 1;
end
else
inherited;
end;
procedure Test;
var
s: TStrength;
u: TUpgrade;
begin
s := TStrength.Create;
try
s.Value := 10;
WriteLn( s.ToString( ) );
u := TSomeUpgrade.Create( 10 );
try
s.InteractWith( u );
finally
u.Free;
end;
WriteLn( s.ToString( ) );
u := TSomeOtherUpgrade.Create( 10 );
try
s.InteractWith( u );
finally
u.Free;
end;
WriteLn( s.ToString( ) );
finally
s.Free;
end;
end;
{ TUpgrade }
constructor TUpgrade.Create( Value: Integer );
begin
inherited Create;
FValue := Value;
end;
begin
try
Test;
except
on E:
Exception do
WriteLn( E.ClassName, '
: ', E.
Message );
end;
ReadLn;
end.