使用设计模式中的状态机模式实现”进程的三态模型扭转“
state.go
package state
import "fmt"
type Process struct {
state State
}
func (p *Process) Run() {
p.state.Run(p)
}
func (p *Process) Pending() {
p.state.Pending(p)
}
func (p *Process) Wait() {
p.state.Wait(p)
}
func (p *Process) TimeOut() {
p.state.TimeOut(p)
}
func NextProcess(state State) Process {
return Process{
state: state,
}
}
func (p *Process) SetState(state State) {
p.state = state
}
type State interface {
Run(*Process)
Pending(*Process)
Wait(*Process)
TimeOut(*Process)
}
type RunProcess struct{}
func (r RunProcess) Run(process *Process) {
fmt.Println("error")
}
func (r RunProcess) Pending(process *Process) {
fmt.Println("error")
}
func (r RunProcess) Wait(process *Process) {
fmt.Println("等待某事件")
process.SetState(BlockProcess{})
}
func (r RunProcess) TimeOut(process *Process) {
fmt.Println("时间片到")
process.SetState(PendingProcess{})
}
type PendingProcess struct{}
func (p PendingProcess) Run(process *Process) {
fmt.Println("调度")
process.SetState(RunProcess{})
}
func (p PendingProcess) Pending(process *Process) {
fmt.Println("error")
}
func (p PendingProcess) Wait(process *Process) {
fmt.Println("error")
}
func (p PendingProcess) TimeOut(process *Process) {
fmt.Println("error")
}
type BlockProcess struct{}
func (b BlockProcess) Run(process *Process) {
fmt.Println("error")
}
func (b BlockProcess) Pending(process *Process) {
fmt.Println("IO结束或者等待时事件发生")
process.SetState(PendingProcess{})
}
func (b BlockProcess) Wait(process *Process) {
fmt.Println("error")
}
func (b BlockProcess) TimeOut(process *Process) {
fmt.Println("error")
}
复制代码
state_test.go
package state
import (
"fmt"
"testing"
)
func TestName(t *testing.T) {
p := NextProcess(PendingProcess{})
p.TimeOut()
p.Run()
p.TimeOut()
p.Run()
fmt.Println("=====")
p.Pending()
p.Wait()
p.Pending()
p.Wait()
fmt.Println("=====")
p.Run()
p.Wait()
p.Pending()
p.Run()
}
复制代码
=== RUN TestName
error
调度
时间片到
调度
=====
error
等待某事件
IO结束或者等待时事件发生
error
=====
调度
等待某事件
IO结束或者等待时事件发生
调度
复制代码