美文网首页
Golang状态模式

Golang状态模式

作者: 黑手党老k | 来源:发表于2019-05-06 10:59 被阅读0次
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状态模式

      本文链接:https://www.haomeiwen.com/subject/mjqroqtx.html