"Cold River Snow" go implement observer mode

Source: Internet
Author: User
Observer Pattern

The Observer pattern allows an instance of one type to send events to other types, provided that the instance receiving the event is subscribed to the event by the root sender. Implement

First, define the interface to use

Package observer

Type (
    event struct{
        Data Int64
    }

    Observer interface{
        onnotify (event)
    }

    Notifier interface{
        Register (Observer)

        degister (Observer)

        Notify (Event)
    }
)

Then write a few simple types to implement these interfaces

Package observer

Import "FMT"

type Eventcenter struct{
    observers []observer
}

func (this * Eventcenter) Notify (event event) {for
    _,v:=range this.observers{
        v.onnotify (event)
    }
}


func ( This *eventcenter) Register (o Observer) {
    this.observers=append (this.observers,o)
}

func (this * Eventcenter) Degister (o Observer) {for
    i:=0;i<len (this.observers); i++{
        if this.observers[i]==o{
            This.observers=append (this.observers[:i],this.observers[i+1:] ...)
            Break
        }
    }
}

func neweventcenter () *eventcenter{
    res: = eventcenter{}
    res.observers= Make ([]observer,0]
    return &res
}


type Eventreciver struct{

}

func (this *eventreciver) OnNotify (Event event) {
    FMT. Printf ("Event receive:%d\n", event.) Data)
}

Finally, the main file

Package Main

func main () {
    Eventcenter: = Observer. Neweventcenter ()
    r_1: = Observer. eventreciver{}
    r_2: = Observer. eventreciver{}

    Eventcenter.register (&r_1)
    eventcenter.register (&r_2)
    eventcenter.notify ( Observer. Event{1})
    Eventcenter.degister (&r_1)
    eventcenter.notify (Observer. EVENT{2})
}
Money to hold a court, no money in the holding of personal field. It's not easy to come out.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.