Skip to content

Commit

Permalink
Add Observer Pattern 馃帀 (#20)
Browse files Browse the repository at this point in the history
  • Loading branch information
willnguyen1312 committed Jun 27, 2023
1 parent 5c6bcc5 commit 688e38d
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 0 deletions.
79 changes: 79 additions & 0 deletions observer.go
@@ -0,0 +1,79 @@
package patterns

import "fmt"

// Subject interface
type Subject interface {
Register(Subscriber)
Deregister(Subscriber)
NotifyAll()
}

// Product struct
type Product struct {
SubscriberList []Subscriber
name string
inStock bool
}

// NewProduct function create a brand-new Product
func NewProduct(name string) *Product {
return &Product{
name: name,
}
}

// UpdateAvailability method on Product struct
func (i *Product) UpdateAvailability() {
i.inStock = true
i.NotifyAll()
}

// Register method on Product struct
func (i *Product) Register(o Subscriber) {
i.SubscriberList = append(i.SubscriberList, o)
}

// Deregister method on Product struct
func (i *Product) Deregister(o Subscriber) {
i.SubscriberList = removeFromslice(i.SubscriberList, o)
}

// NotifyAll method on Product struct
func (i *Product) NotifyAll() {
for _, Subscriber := range i.SubscriberList {
Subscriber.Update(i.name)
}
}

func removeFromslice(SubscriberList []Subscriber, observerToRemove Subscriber) []Subscriber {
observerListLength := len(SubscriberList)
for i, Subscriber := range SubscriberList {
if observerToRemove.GetID() == Subscriber.GetID() {
SubscriberList[observerListLength-1], SubscriberList[i] = SubscriberList[i], SubscriberList[observerListLength-1]
return SubscriberList[:observerListLength-1]
}
}
return SubscriberList
}

// Subscriber interface
type Subscriber interface {
Update(string)
GetID() string
}

// Customer struct
type Customer struct {
id string
}

// Update method on Custome struct
func (c *Customer) Update(itemName string) {
fmt.Printf("Tell customer %s for new product %s\n", c.id, itemName)
}

// GetID method on Customer struct
func (c *Customer) GetID() string {
return c.id
}
13 changes: 13 additions & 0 deletions observer_test.go
@@ -0,0 +1,13 @@
package patterns

func ExampleSubscriber() {
shirtItem := NewProduct("Go React")
firstCustomer := &Customer{id: "vue@yahoo.com"}
secondCustomer := &Customer{id: "angular@yahoo.com"}
shirtItem.Register(firstCustomer)
shirtItem.Register(secondCustomer)
shirtItem.UpdateAvailability()
// Output:
// Tell customer vue@yahoo.com for new product Go React
// Tell customer angular@yahoo.com for new product Go React
}

0 comments on commit 688e38d

Please sign in to comment.