You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

60 lines
751 B

package state
import "fmt"
type State interface {
On(m *Machine)
Off(m *Machine)
}
type Machine struct {
current State
}
func NewMachine() *Machine {
return &Machine{NewOff()}
}
func (m *Machine) On() {
m.current.On(m)
}
func (m *Machine) Off() {
m.current.On(m)
}
func (m *Machine) setCurrent(s State) {
m.current = s
}
type On struct {
}
func NewOn() State {
return &On{}
}
func (o *On) On(m *Machine) {
fmt.Println("从On到Off")
m.setCurrent(NewOff())
}
func (o *On) Off(m *Machine) {
fmt.Println("已经开启")
}
type Off struct {
}
func NewOff() State {
return &Off{}
}
func (o *Off) On(m *Machine) {
fmt.Println("从Off到On")
m.setCurrent(NewOn())
}
func (o *Off) Off(m *Machine) {
fmt.Println("已经关闭")
}