go-pattern-examples/behavior/10_state/state_clock.go

49 lines
1.2 KiB
Go
Raw Normal View History

2020-05-05 17:43:54 +03:00
// Package state is an example of the State Pattern.
package state
////////////////////////////////
//闹装有两种状态,震铃状态,非震铃状态
2020-05-06 06:13:33 +03:00
// AlertStater provides a common interface for various states.
type AlertStater interface {
2020-05-05 17:43:54 +03:00
Alert() string
}
2020-05-06 06:13:33 +03:00
// Alert implements an alert depending on its state.
type Alert struct {
state AlertStater
2020-05-05 17:43:54 +03:00
}
2020-05-06 06:13:33 +03:00
// Alert returns a alert string 代表振铃
func (a *Alert) Alert() string {
2020-05-05 17:43:54 +03:00
return a.state.Alert()
}
// SetState changes state
2020-05-06 06:13:33 +03:00
func (a *Alert) SetState(state AlertStater) {
2020-05-05 17:43:54 +03:00
a.state = state
}
2020-05-06 06:13:33 +03:00
// NewAlert is the Alert constructor默认振铃是震动
func NewAlert() *Alert {
return &Alert{state: &AlertVibration{}}
2020-05-05 17:43:54 +03:00
}
2020-05-06 06:13:33 +03:00
// AlertVibration implements vibration alert
type AlertVibration struct {
2020-05-05 17:43:54 +03:00
}
2020-05-06 06:13:33 +03:00
// Alert returns a alert string ,默认振铃
func (a *AlertVibration) Alert() string {
2020-05-05 17:43:54 +03:00
return "vibrating humming ... vibrating humming...vibrating humming..."
}
2020-05-06 06:13:33 +03:00
// AlertSong implements beep alert
type AlertSong struct {
2020-05-05 17:43:54 +03:00
}
2020-05-06 06:13:33 +03:00
// Alert returns a new alert string 歌曲振铃,设置这个状态模式,闹钟只会唱歌
func (a *AlertSong) Alert() string {
2020-05-05 17:43:54 +03:00
return "sun rise ,get up ,get up get up..."
}