-
Notifications
You must be signed in to change notification settings - Fork 41
/
StatePattern.cs
119 lines (96 loc) · 2.61 KB
/
StatePattern.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
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
//-------------------------------------------------------------------------------------
// StatePatternExample5.cs
//
//-------------------------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace StatePattern
{
public class StatePattern : MonoBehaviour
{
void Start()
{
UnitTest();
}
void UnitTest()
{
Context theContext = new Context();
theContext.SetState(new ConcreteStateA(theContext));
theContext.Request(5);
theContext.Request(15);
theContext.Request(25);
theContext.Request(35);
}
}
/// <summary>
/// Context类-持有目前的状态,并将相关信息传给状态
/// </summary>
public class Context
{
State m_State = null;
public void Request(int Value)
{
m_State.Handle(Value);
}
public void SetState(State theState)
{
Debug.Log("Context.SetState:" + theState);
m_State = theState;
}
}
/// <summary>
/// 状态的抽象基类
/// </summary>
public abstract class State
{
protected Context m_Context = null;
public State(Context theContext)
{
m_Context = theContext;
}
public abstract void Handle(int Value);
}
/// <summary>
/// 状态A
/// </summary>
public class ConcreteStateA : State
{
public ConcreteStateA(Context theContext) : base(theContext)
{ }
public override void Handle(int Value)
{
Debug.Log("ConcreteStateA.Handle");
if (Value > 10)
m_Context.SetState(new ConcreteStateB(m_Context));
}
}
/// <summary>
/// 状态B
/// </summary>
public class ConcreteStateB : State
{
public ConcreteStateB(Context theContext) : base(theContext)
{ }
public override void Handle(int Value)
{
Debug.Log("ConcreteStateB.Handle");
if (Value > 20)
m_Context.SetState(new ConcreteStateC(m_Context));
}
}
/// <summary>
/// 状态C
/// </summary>
public class ConcreteStateC : State
{
public ConcreteStateC(Context theContext) : base(theContext)
{ }
public override void Handle(int Value)
{
Debug.Log("ConcreteStateC.Handle");
if (Value > 30)
m_Context.SetState(new ConcreteStateA(m_Context));
}
}
}