Skip to content

Go Implementation of Observer using generics

License

Notifications You must be signed in to change notification settings

ltunc/go-observer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Go Observer

goreportcard

Implementation of the observer pattern using generics.

Installation

go get github.com/ltunc/go-observer@latest

Usage

package main

import (
	"fmt"
	"github.com/ltunc/go-observer/observer"
)

func main() {
	es := &observer.Subject[Event]{}
	p := &Printer{}
	es.Subscribe(p)
	f := &Fancy{}
	es.Subscribe(f)
	for i := 1; i < 4; i++ {
		e := Event{name: fmt.Sprintf("e%d", i)}
		es.Fire(e)
	}
}

type Event struct {
	name string
}

func (e Event) Name() string {
	return e.name
}

type Printer struct {
}

func (p *Printer) Notify(ev Event) {
	fmt.Println(ev.Name())
}

type Fancy struct {
}

func (r *Fancy) Notify(ev Event) {
	fmt.Printf("Event '%s', hurray!\n", ev.Name())
}

About

Go Implementation of Observer using generics

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages