diff --git a/README.md b/README.md index 4336e3f..4b33677 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ -![alt text][gooopher] - -[gooopher]:https://raw.githubusercontent.com/ismayilmalik/golang-design-patterns/master/gopher.jpg "Gooopher.." +design patterns logo +
+
# Design patterns in golang >A beginner guide... happy coding! @@ -20,6 +20,7 @@ - [Behavioral patterns](#behavioral-patterns) - [Chain of responsibility](#chain-of-responsibility) - [Strategy](#strategy) + - [Observer](#observer) - [Concurrency patterns](#concurrency-patterns) --- @@ -78,5 +79,8 @@ request along the chain until an object handles it. Define a family oafl gorit h ms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. +### Observer +Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically + ## Concurrency patterns Pattenrs for concurrent work and parallel execution in Go. diff --git a/behavioral/observer/observer.go b/behavioral/observer/observer.go new file mode 100644 index 0000000..5d2c760 --- /dev/null +++ b/behavioral/observer/observer.go @@ -0,0 +1,38 @@ +package observer + +import ( + "fmt" +) + +type Observer interface { + Notify(string) +} + +type Publisher struct { + ObserverList []Observer +} + +func (p *Publisher) Subscribe(o Observer) { + p.ObserverList = append(p.ObserverList, o) +} + +func (p *Publisher) Unsubscribe(o Observer) { + var index int + for i, v := range p.ObserverList { + if v == o { + index = i + break + } + } + + p.ObserverList = append(p.ObserverList[:index], p.ObserverList[index + 1:]...) +} + +func (p *Publisher) Publish(m string) { + fmt.Println("Got new message! Publishing...") + for _, o := range p.ObserverList { + o.Notify(m) + } + fmt.Println("Puplished!") +} + diff --git a/logo.png b/logo.png new file mode 100644 index 0000000..65b2f5a Binary files /dev/null and b/logo.png differ diff --git a/structural/proxy/proxy.go b/structural/proxy/proxy.go new file mode 100644 index 0000000..e69de29