下面示例**中,模擬context有兩個狀態,concretestatea與concretestateb,當context呼叫request()方法,觸發concretestatea轉移為concretestateb。
/*
*state pattern
* */
using system;
using system.collections.generic;
namespace pattern03
}abstract
class
state
class
concretestatea
:state
}class
concretestateb
:state
}class
context
public
state state
set}
public
void
request()
}}
示例**狀態轉移圖
/*
* state pattern
*/using system;
using system.collections;
namespace pattern02
}///
/// state
///
abstract
class
state
set}
public
double balance
set}
public
abstract
void
deposit
(double amount)
;public
abstract
void
withdraw
(double amount)
;public
abstract
void
payinterest()
;}class
redstate
:state
public
redstate
(account account,
double balance)
private
void
initialize()
public
override
void
deposit
(double amount)
public
override
void
withdraw
(double amount)
public
override
void
payinterest()
private
void
statechangecheck()
}}class
silverstate
:state
public
silverstate
(double balance,
account account)
private
void
initialize()
public
override
void
deposit
(double amount)
public
override
void
withdraw
(double amount)
public
override
void
payinterest()
private
void
statechangecheck()
else
if(balance > upperlimit)}}
class
goldstate
:state
public
goldstate
(double balance,
account account)
private
void
initialize()
public
override
void
deposit
(double amount)
public
override
void
withdraw
(double amount)
public
override
void
payinterest()
private
void
statechangecheck()
else
if(balance < lowerlimit)}}
///
/// context class
///
class
account
// properties
public
double balance
}public
state state
set}
public
void
deposit
(double amount)
--- "
, amount)
; console.
writeline
(" 當前餘額 = "
,this
.balance)
; console.
writeline
(" 賬戶狀態 = "
,this
.state.
gettype()
.name)
; console.
writeline(""
);}public
void
withdraw
(double amount)
--- "
, amount)
; console.
writeline
(" 當前餘額 = "
,this
.balance)
; console.
writeline
(" 賬戶狀態 = \n"
,this
.state.
gettype()
.name);}
public
void
payinterest()
",this
.balance)
; console.
writeline
(" 賬戶狀態 = \n"
,this
.state.
gettype()
.name);}
}}
狀態模式,關鍵是搞清楚各狀態之間的轉移。也就是狀態(state)、事件(event)、動作(action)之間事件觸發的狀態轉移及動作執行。 變化多端的狀態模式 State Pattern
現在寫字樓越建越高,碼農上個班不但要擠個地鐵,還要擠個電梯。電梯的執行簡單有這麼幾個狀態 執行 停止 關閉 開啟,電梯想要正常的執行,就必須得遵循一定的規則,例如執行的時候不能開門,開門狀態不能執行。按照平常的邏輯,分別建立open,close,run,stop四個方法,方法裡通過switch當前的...
設計模式 設計模式
物件導向程式設計 oop 的基本概念有 封裝,抽象,繼承,多型等,如何開發出可復用的物件導向軟體一直困擾著軟體開發人員。可復用的物件導向技術包括類的繼承,物件的組合和引數化型別 generic gof的巨著 設計模式 總結出可復用的物件導向的23個設計模式,並且歸類成 建立型模式,結構型模式和行為型...
設計模式 命令設計模式
一句話總結 命令設計模式的實質是將命令定義,命令的執行分離開,從而提公升了系統的解藕性 結構 命令的抽象command 命令的具體實現concretecommand 命令處理者抽象ireceiver 命令處理者的具體實現concretereceiver 命令的呼叫者invoker 客戶端client...