implemented observer pattern

This commit is contained in:
ismayilmalik 2018-01-13 23:49:30 +04:00
parent 81c20c5cb7
commit 0580ec9c6e
4 changed files with 45 additions and 3 deletions

View File

@ -1,6 +1,6 @@
![alt text][gooopher] <img src="logo.png" alt="design patterns logo" align="center" />
<br />
[gooopher]:https://raw.githubusercontent.com/ismayilmalik/golang-design-patterns/master/gopher.jpg "Gooopher.." <br />
# Design patterns in golang # Design patterns in golang
>A beginner guide... happy coding! >A beginner guide... happy coding!
@ -20,6 +20,7 @@
- [Behavioral patterns](#behavioral-patterns) - [Behavioral patterns](#behavioral-patterns)
- [Chain of responsibility](#chain-of-responsibility) - [Chain of responsibility](#chain-of-responsibility)
- [Strategy](#strategy) - [Strategy](#strategy)
- [Observer](#observer)
- [Concurrency patterns](#concurrency-patterns) - [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. 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. 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 ## Concurrency patterns
Pattenrs for concurrent work and parallel execution in Go. Pattenrs for concurrent work and parallel execution in Go.

View File

@ -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!")
}

BIN
logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

View File