[go] using function type to realize callback in encapsulation

Time:2021-1-2

When developing business logic, we often need to encapsulate it into an independent class file, and reserve the API of function type in the attributes of class file

When calling some methods in the class file, the functions in the class properties are also called according to the business needs,

In the main business, specific functions can be passed to register in the property, and they will also be called to the property

test.php 

package main

import "log"

func main() {
    c := NewConn(callback, callback2)
    c.Start()
}

//The callback function defined in the current module
func callback() {
    log.Println("i am callback")
}
func callback2(name string) string {
    log.Println("i am callback2 ", name)
    return "hello"
}

connection.go It is an encapsulated class file that calls back the functions in the main module of the class

package main
type Connection struct{
    handleFunc func()
    handleFunc2 func(name string)string
}
//The callback function is registered in the properties of the encapsulated class
func NewConn(callback func(),callback2 func(name string)string) *Connection{
    c:=&Connection{
        handleFunc: callback,
        handleFunc2: callback2,
    }
    return c
}
//In some business, the callback function is also executed
func (c *Connection)Start(){
    c.handleFunc()
    c.handleFunc2("taoshihan")
}

 

Recommended Today

Parsing c + + STL container list is different from Python list

class template std::list preface 📄Content of this article:C++ STL list 📇 Column:C/C++ | Comprehensive understanding of C + + STL Standard Template Library 👤 Author URI :Bauhinia fish 📆 Creation time:2022-1-3 📟 Little tip: the article is very long and detailed. It is recommended to collect it first 🔙Return to directory (recommended Collection):Comprehensive understanding of […]