package patterns // Observer pattern implementation in Go type Observer interface { Update() } // Subject interface defines methods for registering, unregistering, and notifying observers type Subject interface { Register(o Observer) Unregister(o Observer) Notify() } // Concrete implementation of the Subject interface. Lowercase 'subject' to make it unexported, as it will be created through the NewSubject function. type subject struct { observers map[Observer]bool // Using a map to store observers for efficient add/remove operations } // NewSubject creates and returns a new instance of the subject func NewSubject() Subject { // Needs to return a pointer to the subject struct to ensure that the same instance is modified when registering/unregistering observers return &subject{ observers: make(map[Observer]bool), } } // Register adds an observer to the subject's set of observers // Pointer receiver is used to modify the subject's state (the observers map) when registering an observer func (s *subject) Register(o Observer) { s.observers[o] = true } // Unregister removes an observer from the subject's set of observers // Pointer receiver is used to modify the subject's state (the observers map) when unregistering an observer func (s *subject) Unregister(o Observer) { delete(s.observers, o) } // Notify calls the Update method on all registered observers to notify them of a change func (s *subject) Notify() { for o := range s.observers { o.Update() } }