我即将使用状态模式在C#中实现分层状态机.作为指导,我正在使用这个例子.但是,该示例并未提供有关分层状态的答案.不幸的是,我似乎无法在其他地方找到好的例子.我的第一个想法是为分层状态创建嵌套类.但这被认为是最佳实践还是有更好的解决方案?
映入眼帘!
更新:
我整个下午一直坐着试图实现如上所述的状态模式.HSM基于一个非常简单的媒体播放器:
alt text http://www.freeimagehosting.net/uploads/e8d2d6486a.jpg
我以为我已经做到了,但有一点我不明白.首先是我写的代码(抱歉,它非常多):
public class MediaPlayer
{
public MediaPlayerStates state;
public MediaPlayer(MediaPlayerStates state)
{
this.state = state;
}
public void OnButtonPressed()
{
state.OnButtonPressed(this);
}
public void DeviceBooted()
{
state. ?????
}
//Other Functions
}
//The 3 initial states (Start, On, End) know only 2 events.
public abstract class MediaPlayerStates
{
public abstract void OnButtonPressed(MediaPlayer player);
public abstract void OffButtonPressed(MediaPlayer player);
}
//The very beginpoint of the state machine
public class Start : MediaPlayerStates …Run Code Online (Sandbox Code Playgroud) 我正在尝试生成一个随机长度的字符串,该字符串由随机chars组成.
为此,我有这样的代码:
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 1000; i++)
{
MyString test = new MyString();
test.Random();
Console.WriteLine(test.Value);
}
Console.ReadLine();
}
}
public class MyString
{
private string value = string.Empty;
private Random r = new Random();
public string Value
{
get { return this.value; }
set { this.value = value; }
}
public void Random()
{
int length = (r.Next() % (100)) + 1;
for(int i = 0; …Run Code Online (Sandbox Code Playgroud)