-
-
Save sandeepone/073c962c16bba687ca11ca48d3cf7ae0 to your computer and use it in GitHub Desktop.
Observer pattern - golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type TestCallBack struct { | |
} | |
func (c *TestCallBack) Exec(o *Observable) { | |
log.Println(o.Name) | |
} | |
type Callback interface { | |
Exec(h *Observable) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
) | |
type Observable struct { | |
Name string | |
} | |
type TestCallBack struct { | |
} | |
func (c *TestCallBack) Exec(o *Observable) { | |
log.Println(o.Name) | |
} | |
type Callback interface { | |
Exec(h *Observable) | |
} | |
type Observer struct { | |
callbacks []Callback | |
} | |
func (o *Observer) Add(c Callback) { | |
o.callbacks = append(o.callbacks, c) | |
} | |
func (o *Observer) Process(oe *Observable) { | |
for _, c := range o.callbacks { | |
c.Exec(oe) | |
} | |
} | |
func main() { | |
oe := Observable{Name: "Hello World"} | |
o := Observer{} | |
o.Add(&TestCallBack{}) | |
o.Process(&oe) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Observer struct { | |
callbacks []Callback | |
} | |
func (o *Observer) Add(c Callback) { | |
o.callbacks = append(o.callbacks, c) | |
} | |
func (o *Observer) Process(oe *Observable) { | |
for _, c := range o.callbacks { | |
c.Exec(oe) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment