-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStateContext.cs
59 lines (51 loc) · 1.79 KB
/
StateContext.cs
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
namespace GofPatterns.Behavioral.StatePattern;
/// <summary>
/// Context class for state pattern.
/// It is responsible for holding the current state, executing the state, and changing the state.
/// It can be directly used as a context class, or inherited by other classes to make them context.
/// </summary>
/// <typeparam name="TContext">IStateContext</typeparam>
public class StateContext<TContext> : IStateContext<TContext> where TContext : IStateContext<TContext>
{
public StateContext(IState<TContext> defaultState)
{
State = defaultState;
}
public void SetState(IState<TContext> state)
{
State = state;
}
public virtual void Execute()
{
object thisObject = this;
var context = (TContext) thisObject;
State.Execute(context);
}
public IState<TContext> State { get; private set; }
}
/// <summary>
/// Context class for state pattern.
/// It is responsible for holding the current state, executing the state, and changing the state.
/// It can be directly used as a context class, or inherited by other classes to make them context.
/// It returns a value after execution.
/// </summary>
/// <typeparam name="TContext">IStateContext</typeparam>
/// <typeparam name="TOut">Output</typeparam>
public class StateContext<TContext, TOut> : IStateContext<TContext, TOut> where TContext : IStateContext<TContext, TOut>
{
public StateContext(IState<TContext, TOut> defaultState)
{
State = defaultState;
}
public void SetState(IState<TContext, TOut> state)
{
State = state;
}
public virtual TOut Execute()
{
object thisObject = this;
var context = (TContext) thisObject;
return State.Execute(context);
}
public IState<TContext, TOut> State { get; private set; }
}