ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 示例 ### 有货时通知客户 <details> <summary>main.go</summary> ``` package main import "fmt" // 主体 type subject interface { register(Observer observer) deregister(Observer observer) notifyAll() } // 具体主体 type item struct { observerList []observer name string inStock bool // 是否有货 } func newItem(name string) *item { return &item{ name: name, } } func (i *item) updateAvailability() { fmt.Printf("Item %s is now in stock\n", i.name) i.inStock = true i.notifyAll() } func (i *item) register(o observer) { i.observerList = append(i.observerList, o) } func (i *item) deregister(o observer) { i.observerList = i.removeFromslice(i.observerList, o) } func (i *item) notifyAll() { for _, observer := range i.observerList { observer.update(i.name) } } func (i *item) removeFromslice(observerList []observer, observerToRemove observer) []observer { observerListLength := len(observerList) for i, observer := range observerList { if observerToRemove.getID() == observer.getID() { observerList[observerListLength-1], observerList[i] = observerList[i], observerList[observerListLength-1] return observerList[:observerListLength-1] } } return observerList } // 观察者 type observer interface { update(string) getID() string } // 具体观察者 type customer struct { id string } func (c *customer) update(itemName string) { fmt.Printf("Sending email to customer %s for item %s\n", c.id, itemName) } func (c *customer) getID() string { return c.id } func main() { shirtItem := newItem("Nike Shirt") observerFirst := &customer{id: "abc@gmail.com"} observerSecond := &customer{id: "xyz@gmail.com"} shirtItem.register(observerFirst) shirtItem.register(observerSecond) shirtItem.updateAvailability() } ``` </details> <br /> 输出 ``` Item Nike Shirt is now in stock Sending email to customer abc@gmail.com for item Nike Shirt Sending email to customer xyz@gmail.com for item Nike Shirt ```