SoFunction
Updated on 2025-03-05

Go design pattern explanation and code example

Concept example

In e-commerce websites, products are out of stock from time to time. There may be customers who show interest in specific items out of stock. There are three solutions to this problem:

  • Customers view product availability at a certain frequency.
  • The e-commerce website sends customers all new products in stock.
  • Customers subscribe to only specific items they are interested in and will be notified when the items are available. At the same time, multiple customers can also subscribe to the same product.

Option 3 is the most feasible, which is actually the idea of ​​the observer pattern. The main components of the observer pattern are:

  • The subject that publishes the event when anything happens.
  • Observer who subscribes to the subject event and receives notification when the event occurs.

:main body

package main
type Subject interface {
	register(observer Observer)
	deregister(obs Observer)
	notifyAll()
}

:Specific subject

package main
import (
	"fmt"
)
type Item struct {
	observerList []Observer // Multiple observers	name         string
	inStock      bool // In stock}
func newItem(name string) *Item {
	return &Item{
		name:    name,
		inStock: false,
	}
}
// Update statusfunc (i *Item) updateAvailability() {
	("Item %s is now in stock \n", )
	 = true // Update status, stock s	()
}
func (i *Item) register(o Observer) {
	 = append(, o)
}
func (i *Item) deregister(o Observer) {
	 = removeFromslice(, o)
}
func (i *Item) notifyAll() {
	for _, v := range  {
		()
	}
}
func removeFromslice(observerList []Observer, observerToRemove Observer) []Observer {
	observerListLength := len(observerList)
	for i, observer := range observerList {
		if () == () {
			observerList[observerListLength-1], observerList[i] = observerList[i], observerList[observerListLength-1]
			return observerList[:observerListLength-1]
		}
	}
	return observerList
}

:Observer

package main
type Observer interface {
	update(string)
	getID() string
}

:Specific observer

package main
import "fmt"
type Customer struct {
	id string
}
func (c *Customer) getID() string {
	return 
}
func (c *Customer) update(iteName string) {
	("Sendint email to customer %s for item %s\n", , iteName)
}

:Client code

package main
func main() {
	shirtItem := newItem("Nick Shirt")
	observerFirst := &Customer{
		id: "abc@",
	}
	observerSecond := &Customer{
		id: "def@",
	}
	(observerFirst)
	(observerSecond)
	()
}

:Execution results

Item Nick Shirt is now in stock 
Sendint email to customer abc@ for item Nick Shirt
Sendint email to customer def@ for item Nick Shirt

This is the article about the Go Design Pattern Explanation and Code Sample of Observer Mode. For more relevant Go Observer Mode content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!