-
-
Save gengen1988/e75dc254be43dbbd1e46cb9db38f82b7 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
// Observable ... | |
type Observable interface{} | |
// Callback ... | |
type Callback func(Observable) | |
// Human ... | |
type Human struct { | |
name string | |
} | |
// Alien ... | |
type Alien struct { | |
ooo string | |
} |
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 "fmt" | |
func main() { | |
human := &Alien{ooo: "Jack"} | |
humanObserver := Observer{} | |
humanObserver.Add(callName) | |
humanObserver.Process(human) | |
} | |
func callName(o Observable) { | |
human, ok := o.(*Human) | |
if !ok { | |
return | |
} | |
fmt.Println(human.name) | |
} |
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
// Observer ... | |
type Observer struct { | |
callbacks []Callback | |
} | |
// Add ... | |
func (o *Observer) Add(c Callback) { | |
o.callbacks = append(o.callbacks, c) | |
} | |
// Process ... | |
func (o Observer) Process(value Observable) { | |
for _, callback := range o.callbacks { | |
callback(value) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment