Observer pattern is used when there is one-to-many relationship between objects such as if one object is modified, its dependent objects are to be notified automatically. Observer pattern falls under behavioral pattern category.
Here is my implementation in Golang shown as below:
Observer with file interface.go
type ObserverCallBack struct { } func (c *ObserverCallBack) Exec(o *Observable) { log.Println(o.Name) } type Callback interface { Exec(h *Observable) } |
Observer Notifier with file observer.go
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) } } |
Full Code with main.go
package main import ( "log" ) type Observable struct { Name string } type ObserverCallBack struct { } func (c *ObserverCallBack) 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(&ObserverCallBack{}) o.Process(&oe) } | ||
Result shown as below
Other Topics:
How to build NGINX RTMP module, Setup Live Streaming with NGINX RTMP module, Publishing Stream with Open Broadcaster Software (OBS), Create Adaptive Streaming with NGINX RTMP, Implementing Filtergraph in Streaming with NGINX RTMP, How to Implement Running Text in Streaming with NGINX RTMP, How to build OpenSceneGraph with Code::Blocks, How to build OpenSceneGraph with Visual Studio 2010, Building Geometry Model, How to run OpenSceneGraph with Netbean IDE 8.2 C++, Rendering Basic Shapes, Using OSG Node to Load 3D Object Model, Rendering 3D Simulator with OpenSceneGraph, How to compile wxWidgets with Visual Studio 2010, How to Setup Debugging in Golang with Visual Code
No comments:
Post a Comment