-
Notifications
You must be signed in to change notification settings - Fork 77
/
Behavioral.State.Pattern.pas
91 lines (73 loc) · 1.65 KB
/
Behavioral.State.Pattern.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
unit Behavioral.State.Pattern;
interface
type
TContext = class;
IState = interface
['{2E995182-8FA5-4AF2-9994-6E5B7F273A0B}']
function MoveUp(c: TContext): integer;
function MoveDown(c: TContext): integer;
end;
TNormalState = class(TInterfacedObject, IState)
public
function MoveUp(c: TContext): integer;
function MoveDown(c: TContext): integer;
end;
TFastState = class(TInterfacedObject, IState)
public
function MoveUp(c: TContext): integer;
function MoveDown(c: TContext): integer;
end;
TContext = class
const
LIMIT = 10;
public
FState: IState;
FCounter: integer;
constructor Create;
function Request(i: integer): integer;
end;
implementation
{ TNormalState }
function TNormalState.MoveDown(c: TContext): integer;
begin
if c.FCounter < c.LIMIT then begin
c.FState := TFastState.Create;
WriteLn('|| ');
end;
c.FCounter := c.FCounter - 2;
Result := c.FCounter;
end;
function TNormalState.MoveUp(c: TContext): integer;
begin
c.FCounter := c.FCounter + 2;
Result := c.FCounter;
end;
{ TFastState }
function TFastState.MoveDown(c: TContext): integer;
begin
if c.FCounter < c.LIMIT then begin
c.FState := TNormalState.Create;
WriteLn('|| ');
end;
c.FCounter := c.FCounter - 5;
Result := c.FCounter;
end;
function TFastState.MoveUp(c: TContext): integer;
begin
c.FCounter := c.FCounter + 5;
Result := c.FCounter;
end;
{ TContext }
constructor TContext.Create;
begin
inherited;
FCounter := LIMIT;
end;
function TContext.Request(i: integer): integer;
begin
if i = 2 then
Result := FState.MoveUp(Self)
else
Result := FState.MoveDown(Self);
end;
end.