golang如何實現插件化編程


package main
import ("fmt")
 
// 定義一個接口,里面有兩個方法
type pluginfunc interface {
    hello()
    world()
}
// 定義一個類,來存放我們的插件
type plugins struct {
    plist map[string] pluginfunc
}
// 初始化插件
func (p *plugins)init(){
    p.plist = make(map[string]pluginfunc)
}
// 注冊插件
 
func (p *plugins)register(name string, plugin pluginfunc) {
        p.plist[name] = plugin
        //p.plist = append(p.plist, a)
 
}
//plugin1
type plugin1 struct {}
func (p *plugin1) hello (){
    fmt.Println("plugin1 hello")
}
func (p *plugin1) world (){
    fmt.Println("plugin1 world")
}
//plugin2
type plugin2 struct {}
func (p *plugin2) hello() {
    fmt.Println("plugin2 hello")
}
func (p *plugin2) world (){
    fmt.Println("plugin2 world")
}
//plugin3
type plugin3 struct {}
func (p *plugin3) hello() {
    fmt.Println("plugin3 hello")
}
func (p *plugin3) world (){
    fmt.Println("plugin3 world")
}

定義了三個插件,plugin1, plugin2, plugin3, 都實現hello和world的方法。

接下來在我們的main函數中,

func main() {
    plugin := new(plugins)
    plugin.init()
 
    plugin1 := new(plugin1)
    plugin2 := new(plugin2)
    plugin3 := new(plugin3)
    plugin.register("plugin1",plugin1)
    plugin.register("plugin2",plugin2)
    plugin.register("plugin3",plugin3)
    for _,plugin := range(plugin.plist) {
        plugin.hello()
        plugin.world()
    }
}

在main中,我們直接將這三個插件register,然后循環調用即可。

如果有插件4,我們只需要定義plugin4, 然后plugin.register("plugin4", plugin4) 即可。

golang的interface還是很靈活的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM