type Call interface {
String() string
}
type Cn struct {
}
type En struct {
}
func Newcn() Call {
return &Cn{}
}
func (c *Cn) String() string {
b, _ := json.Marshal(c)
fmt.Println(b)
return string(b)
}
func Newen() Call {
return &En{}
}
func (e *En) String() string {
b, _ := json.Marshal(e)
fmt.Println("test")
return string(b)
}
func main() {
var calls []Call = []Call{Newcn(), Newen()}
for _, v := range calls {
v.String()
}
}
package main
import (
"encoding/json"
"fmt"
"time"
)
type Keyword struct {
word string
visit int
UpdatedAt *time.Time
}
// Clone 这里使用序列化与反序列化的方式深拷贝
func (k *Keyword) Clone() *Keyword {
var newKeyword Keyword
b, _ := json.Marshal(k)
json.Unmarshal(b, &newKeyword)
return &newKeyword
}
// Keywords 关键字 map
type Keywords map[string]*Keyword
// Clone 复制一个新的 keywords
// updatedWords: 需要更新的关键词列表,由于从数据库中获取数据常常是数组的方式
func (words Keywords) Clone(updatedWords []*Keyword) Keywords {
newKeywords := map[string]*Keyword{}
for k, v := range words {
// 这里是浅拷贝,直接拷贝了地址
newKeywords[k] = v
}
// 替换掉需要更新的字段,这里用的是深拷贝
for _, word := range updatedWords {
newKeywords[word.word] = word.Clone()
}
return newKeywords
}
-----------
type Call interface {
EnterState()
Lightx()
NextLightx(c *Default)
}
type Default struct {
Opet Call
}
func NewDefault() *Default {
return &Default{Opet: RedP()}
}
func (d *Stat) EnterState() {
fmt.Println("changed state to:", d.status)
}
func (d *Default) TransitionState(ca Call) { //一定要实现call接口三个方法
// EnterState()
// Lightx()
// NextLightx(c *Default)
d.Opet = ca
d.Opet.EnterState()
}
type Stat struct {
status string
}
type Redstat struct {
Stat
}
type GreeStat struct {
Stat
}
func RedP() *Redstat {
return &Redstat{Stat{status: "RED"}}
}
func (r *Redstat) Lightx() {
fmt.Println("红灯亮起,不可行驶")
}
func (r *Redstat) NextLightx(c *Default) {
c.TransitionState(NewGreeStat())
}
func NewGreeStat() *GreeStat {
return &GreeStat{Stat{status: "Gree"}}
}
func (g *GreeStat) Lightx() {
fmt.Println("lv灯亮起,可行驶")
}
func (g *GreeStat) NextLightx(c *Default) {
c.TransitionState(NewAmberStatex())
}
type amberStatex struct {
Stat
}
func NewAmberStatex() *amberStatex {
statex := &amberStatex{}
statex.status = "AMBER"
return statex
}
func (statex *amberStatex) Lightx() {
fmt.Println("黄灯亮起,请注意")
}
func (statex *amberStatex) NextLightx(d *Default) {
d.TransitionState(RedP())
}
func main() {
p := NewDefault()
ticker := time.NewTicker(5 * time.Millisecond)
for {
select {
case <-ticker.C:
// p.Opet.EnterState()
p.Opet.Lightx()
p.Opet.NextLightx(p)
default:
}
}
}