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:
}
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
2022-06-17 浅谈Docker-compose中的depends_on顺序的问题解决
2022-06-17 chrony时间同步服务简介及配置
2021-06-17 Filebeat是如何工作的
2019-06-17 用包来组织模型
2019-06-17 使用装饰器配置路由的
2019-06-17 python方法未绑定错误
2019-06-17 NetHogs监控Linux的每个进程流量