Golang 插件式开发

Jackey Golang 5,635 次浏览 没有评论

接口定义:

  1. package testPlugin
  2.  
  3. type PluginFunc interface {
  4. Hello()
  5. World()
  6. }
  7.  
  8. type Plugins struct {
  9. Plist map[string]PluginFunc
  10. }
  11.  
  12. func (p *Plugins) Init() {
  13. p.Plist = make(map[string]PluginFunc)
  14. }
  15.  
  16. func (p *Plugins) Register(name string, plugin PluginFunc) {
  17. p.Plist[name] = plugin
  18. }

插件1

  1. package testPlugin
  2.  
  3. import "fmt"
  4.  
  5. type Plugin1 struct {}
  6.  
  7. func (p *Plugin1) Hello() {
  8. fmt.Println("plugin1 hello")
  9. }
  10.  
  11. func (p *Plugin1) World() {
  12. fmt.Println("plugin1 world")
  13. }

插件2:

  1. package testPlugin
  2.  
  3. import "fmt"
  4.  
  5. type Plugin2 struct {}
  6.  
  7. func (p *Plugin2) Hello() {
  8. fmt.Println("plugin2 hello")
  9. }
  10.  
  11. func (p *Plugin2) World() {
  12. fmt.Println("plugin2 world")
  13. }

插件3:

  1. package testPlugin
  2.  
  3. import "fmt"
  4.  
  5. type Plugin3 struct {}
  6.  
  7. func (p *Plugin3) Hello() {
  8. fmt.Println("plugin3 hello")
  9. }
  10.  
  11. func (p *Plugin3) World() {
  12. fmt.Println("plugin3 world")
  13. }

插件的使用:

  1. package main
  2.  
  3. import (
  4. "test/testPlugin"
  5. )
  6.  
  7. func main() {
  8. plugin := new(testPlugin.Plugins)
  9. plugin.Init()
  10.  
  11. plugin1 := new(testPlugin.Plugin1)
  12. plugin2 := new(testPlugin.Plugin2)
  13. plugin3 := new(testPlugin.Plugin3)
  14.  
  15. plugin.Register("plugin1", plugin1)
  16. plugin.Register("plugin2", plugin2)
  17. plugin.Register("plugin3", plugin3)
  18.  
  19. for _, p := range plugin.Plist {
  20. p.Hello()
  21. p.World()
  22. }
  23. }

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Go