一、狀態模式簡介(Brief Introduction)
狀態模式(State Pattern),當一個對象的內在狀態改變時允許改變其行為,這個對象 看起來像是改變了其類。
二、解決的問題(What To Solve)
狀態模式主要解決的是當控制一個對象狀態裝換的條件表達式過於復雜時的情況。把狀態 的判斷邏輯轉移到表示不同狀態的一系列類中,可以把復雜的判斷邏輯簡單化。
當一個對象行為取決於它的狀態,並且它必須在運行時刻根據狀態改變它的行為時,就可 以考慮使用狀態模式了。
三、狀態模式分析(Analysis)
1、狀態模式結構
Context類:維護一個ConcreteState子類的一個實例,這個實例定義當前的狀態。
State類:抽象狀態類,定義一個接口以封裝與Context的一個特定狀態相關的行為。
ConcreteStateA,ConcreteStateB,ConcreteStateC類:具體狀態類,每一個子類實現一個 與Context的一個狀態相關的行為。
2、源代碼
1、Context類:維護一個ConcreteState子類的一個實例,這個實例定義當前的狀態
public class Context
{
private State state;
public State State
{
get { return state; }
set
{
state = value;
Console.WriteLine("當前狀態是:" + state.GetType ().Name);
}
}
public Context(State state)
{
this.state = state;
Console.WriteLine("初始狀態是:"+state.GetType().Name);
}
public void Request()
{
state.Handle(this);
}
}
2、抽象狀態類及其具體實現類
public abstract class State
{
public abstract void Handle(Context context);
}
public class ConcreteStateA:State
{
public override void Handle(Context context)
{
context.State = new ConcreteStateB();
}
}
public class ConcreteStateB: State
{
public override void Handle(Context context)
{
context.State = new ConcreteStateC();
}
}
public class ConcreteStateC : State
{
public override void Handle(Context context)
{
context.State = new ConcreteStateA();
}
}
4、客戶端代碼
static void Main(string[] args)
{
Context context = new Context(new ConcreteStateA());
context.Request();
context.Request();
context.Request();
Console.Read();
}
3、程序運行結果
四.案例分析(Example)1、場景
銀行賬戶根據余額可分為三種狀態RedState,SilverState,GoldState,這些狀態分別代 表了透支帳戶(overdrawn accounts),新開帳戶(starter accounts),標准帳戶(accounts in good standing)..如下圖所示
RedState類:賬號余額在范圍【0.0,1000.0】表示處於處於SilverState。否則轉換為其 他狀態。
if (balance < lowerLimit)
{
account.State = new RedState(this);
}
else if (balance > upperLimit)
{
account.State = new GoldState(this);
}
SilverState類:賬號余額在范圍【-100.0,0】表示處於處於RedState。否則 轉換為其他狀態。
if (balance > upperLimit)
{
account.State = new SilverState(this);
}
GoldState類:賬號余 額在范圍【1000.0,10000000.0】表示處於處於GoldState。否則轉換為其他狀態。
if (balance < 0.0)
{
account.State = new RedState(this);
}
else if (balance < lowerLimit)
{
account.State = new SilverState(this);
}
2、代碼
1、類Account,相當於Context類
class Account
{
private State _state;
private string _owner;
// Constructor
public Account(string owner)
{
// New accounts are 'Silver' by default
this._owner = owner;
this._state = new SilverState(0.0, this);
}
// Properties
public double Balance
{
get { return _state.Balance; }
}
public State State
{
get { return _state; }
set { _state = value; }
}
public void Deposit(double amount)
{
_state.Deposit(amount);
Console.WriteLine("Deposited {0:C} --- ", amount);
Console.WriteLine(" Balance = {0:C}", this.Balance);
Console.WriteLine(" Status = {0}",
this.State.GetType().Name);
Console.WriteLine ("");
}
public void Withdraw(double amount)
{
_state.Withdraw (amount);
Console.WriteLine("Withdrew {0:C} --- ", amount);
Console.WriteLine(" Balance = {0:C}", this.Balance);
Console.WriteLine(" Status = {0}\n",
this.State.GetType().Name);
}
public void PayInterest()
{
_state.PayInterest();
Console.WriteLine("Interest Paid --- ");
Console.WriteLine(" Balance = {0:C}", this.Balance);
Console.WriteLine(" Status = {0}\n",
this.State.GetType().Name);
}
}
2、抽象狀態類State及其具體狀態類RedState,SilverState,GoldState
/// <summary>
/// The 'State' abstract class
/// </summary>
abstract class State
{
protected Account account;
protected double balance;
protected double interest;
protected double lowerLimit;
protected double upperLimit;
// Properties
public Account Account
{
get { return account; }
set { account = value; }
}
public double Balance
{
get { return balance; }
set { balance = value; }
}
public abstract void Deposit(double amount);
public abstract void Withdraw(double amount);
public abstract void PayInterest();
}
/// <summary>
/// A 'ConcreteState' class
/// <remarks>
/// Red indicates that account is overdrawn
/// </remarks>
/// </summary>
class RedState : State
{
private double _serviceFee;
// Constructor
public RedState(State state)
{
this.balance = state.Balance;
this.account = state.Account;
Initialize();
}
private void Initialize()
{
// Should come from a datasource
interest = 0.0;
lowerLimit = -100.0;
upperLimit = 0.0;
_serviceFee = 15.00;
}
public override void Deposit(double amount)
{
balance += amount;
StateChangeCheck();
}
public override void Withdraw(double amount)
{
amount = amount - _serviceFee;
Console.WriteLine("No funds available for withdrawal!");
}
public override void PayInterest()
{
// No interest is paid
}
private void StateChangeCheck()
{
if (balance > upperLimit)
{
account.State = new SilverState(this);
}
}
}
/// <summary>
/// A 'ConcreteState' class
/// <remarks>
/// Silver indicates a non-interest bearing state
/// </remarks>
/// </summary>
class SilverState : State
{
// Overloaded constructors
public SilverState(State state)
:
this(state.Balance, state.Account)
{
}
public SilverState(double balance, Account account)
{
this.balance = balance;
this.account = account;
Initialize();
}
private void Initialize()
{
// Should come from a datasource
interest = 0.0;
lowerLimit = 0.0;
upperLimit = 1000.0;
}
public override void Deposit(double amount)
{
balance += amount;
StateChangeCheck();
}
public override void Withdraw(double amount)
{
balance -= amount;
StateChangeCheck();
}
public override void PayInterest()
{
balance += interest * balance;
StateChangeCheck();
}
private void StateChangeCheck()
{
if (balance < lowerLimit)
{
account.State = new RedState(this);
}
else if (balance > upperLimit)
{
account.State = new GoldState(this);
}
}
}
/// <summary>
/// A 'ConcreteState' class
/// <remarks>
/// Gold indicates an interest bearing state
/// </remarks>
/// </summary>
class GoldState : State
{
// Overloaded constructors
public GoldState(State state)
: this(state.Balance, state.Account)
{
}
public GoldState(double balance, Account account)
{
this.balance = balance;
this.account = account;
Initialize();
}
private void Initialize()
{
// Should come from a database
interest = 0.05;
lowerLimit = 1000.0;
upperLimit = 10000000.0;
}
public override void Deposit(double amount)
{
balance += amount;
StateChangeCheck();
}
public override void Withdraw(double amount)
{
balance -= amount;
StateChangeCheck();
}
public override void PayInterest()
{
balance += interest * balance;
StateChangeCheck();
}
private void StateChangeCheck()
{
if (balance < 0.0)
{
account.State = new RedState(this);
}
else if (balance < lowerLimit)
{
account.State = new SilverState(this);
}
}
}
3、客戶端代碼
static void Main(string[] args)
{
// Open a new account
Account account = new Account("Jim Johnson");
// Apply financial transactions
account.Deposit(500.0);
account.Deposit(300.0);
account.Deposit(550.0);
account.PayInterest();
account.Withdraw(2000.00);
account.Withdraw(1100.00);
// Wait for user
Console.ReadKey();
}
3、程序運行結果
五、總結(Summary)
狀態模式(State Pattern),當一個對象的內在狀態改變時允許改變其行為,這個對象 看起來像是改變了其類。當一個對象行為取決於它的狀態,並且它必須在運行時刻根據狀態 改變它的行為時,就可以考慮使用狀態模式了。
出處:http://www.cnblogs.com/ywqu