背景
- 前序状态执行后,切换到后续状态
- 与责任链异同
- 责任链:遍历并下放到具体责任者处理要求
- 状态:在不同状态中轮转处理要求
示例
using System;
using static System.Console;
namespace DesignPattern_State
{
// 游戏类 =上下文类
public class Game
{
public IState CurrentPlayer { get; set; }
public void Play()
{
for (int turn = 0; turn < 10; turn++)
{
Write($"#{turn} ");
CurrentPlayer.Handle(turn == 9);
}
}
}
// 状态接口
public interface IState
{
IState Opposite { set; get; }
void Handle(bool won = false);
}
// 玩家类 =具体状态
public class Player : IState
{
private readonly Game game;
private readonly string name;
private Random random = new Random();
// 因互相引用,延迟到属性(非构造器)中初始化
public IState Opposite { set; get; }
public Player(Game game, string name)
{
this.game = game;
this.name = name;
}
public void Handle(bool won = false)
{
string seconds = new string('.', random.Next(1, 5));
Write($"Thinking {seconds}");
string info = won
? $"Player {this} won. Game over."
: $"Player {this} played. Turn to player {Opposite}.";
WriteLine(info);
game.CurrentPlayer = Opposite;
}
public override string ToString() => name;
}
class Program
{
static void Main(string[] args)
{
var game = new Game();
var zhang = new Player(game, "Zhang");
var li = new Player(game, "Li");
zhang.Opposite = li;
li.Opposite = zhang;
game.CurrentPlayer = zhang;
game.Play();
ReadKey();
}
}
}
网友评论