package main
import (
"fmt"
)
// 环境类
type Account struct{
State ActionState
HealthValue int
}
// 状态类
type ActionState interface{
View()
Comment()
Post()
}
// new accout
func NewAccount(health int) *Account{
a:=&Account{
HealthValue: health,
}
a.changeState()
return a
}
// set healthValue for account
func (a *Account) SetHealth(value int){
a.HealthValue = value
a.changeState()
}
func (a *Account) changeState(){
if a.HealthValue <= -10{
a.State=&CloseState{}
}else if a.HealthValue >-10 && a.HealthValue <= 0{
a.State = &Retricted{}
} else if a.HealthValue > 0{
a.State = & NormalState{}
}
}
// state 三种状态
type NormalState struct{}
type Retricted struct{}
type CloseState struct{}
// 封装state 三种状态的不同行为
func (c *CloseState) View(){
fmt.Println("无法查看")
}
func (c *CloseState) Comment(){
fmt.Println("不能评论")
}
func (c *CloseState) Post(){
fmt.Println("不能发布")
}
func (r *Retricted) View(){
fmt.Println("正常")
}
func (r *Retricted) Comment(){
fmt.Println("正常")
}
func (r *Retricted) Post(){
fmt.Println("不能发布")
}
func (r *NormalState) View(){
fmt.Println("正常")
}
func (r *NormalState) Comment(){
fmt.Println("正常")
}
func (r *NormalState) Post(){
fmt.Println("正常")
}
func main() {
}
// golang状态模式写法会多申明很多对像,但是会减少各种判定操作
Golang状态模式
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...