I ran into an a blog All Design Patterns in Go (Golang) but feel that it does not have to be this OOP and this complicated in Go. So I will try to re-implement these patterns in a more Go-ish way.

Behavioural Design Patterns

Observer pattern

Go has very good support for functional programming, making a lot of object-ish wrappers unnecessary.
Instead of having the observer interface receiving a function, I can directly keep track of the functions to be invoked at events:

1
2
3
4
5
type item struct {
observerFuncs map[string]func(string)
name string
inStock bool
}

The functions to notify can be directly be registered to and invoked by the subject:

1
2
3
4
5
6
7
8
9
10
11
12
func (i *item) register(id string) {
if i.notifyFuncs == nil {
i.notifyFuncs = map[string]func(string){}
}
i.notifyFuncs[id] = customerNotificationFunc(id)
}

func (i *item) notifyAll() {
for _, notifyFunc := range i.notifyFuncs {
notifyFunc(i.name)
}
}

Strategy pattern

While I’m here let me implement the caching strategies in full.

  • Extended the item data type to keep track of the accessCount, lastAccessed time and lastUpdated time
  • Implemented the algos - although now not wrapped in an interface but passed in as a function.