Macaron的注入interface

#上一篇 http://my.oschina.net/u/943306/blog/506905
上一篇介紹了Macaron裏的注入Struct,這篇介紹注入interface
二者的區別在於:git

  1. 使用方法不一樣,注入Struct用的是Map,而注入interface的是MapTo
  2. 注入Struct的話,只能用該類型的Struct,而注入interface的話,能夠用任何實現interface的Struct

#先上代碼github

package main

import (
	"fmt"
	"github.com/Unknwon/macaron"
)

func main() {

	m := macaron.Classic()
	m.Use(MidInterface("laoshi")) //底層使用了MapTo而不是Map了

	m.Get("/", func(ctx *macaron.Context, s STUDENT) { //這裏要用接口的方式傳入,而不能用*Student了
		fmt.Println(s.GetName())
		s.Job()  //上面用的是「laoshi」,因此打印的是teach...,改爲「xuesheng」試試結果
	})

	m.Run()
}

    //新添加的,用於代替MidStruct
func MidInterface(opt string) macaron.Handler {
	var s STUDENT
	if opt == "laoshi" {
		s = &Teacher{Id: 1, Name: "xiao ming"}
	} else {
		s = &Student{Id: 1, Name: "xiao wang"}
	}
	return func(ctx *macaron.Context) {
		ctx.MapTo(s, (*STUDENT)(nil)) //MapTo用來註冊interface
	}
}
    
    //MidStruct在這裏沒有用到,用於和MidInterface比較而保留在此
func MidStruct(opt string) macaron.Handler {
	var s *Student
	if opt == "xm" {
		s = &Student{Id: 1, Name: "xiao ming"}
	} else {
		s = &Student{Id: 1, Name: "xiao wang"}
	}

	return func(ctx *macaron.Context) {
		ctx.Map(s)  //Map用來註冊struct
	}
}

    //新加一個STUDENT的接口,下面的Student和Teacher都已經實現了該接口
type STUDENT interface {
	GetName() string
	Job()
}

type Student struct {
	Id   int
	Name string
}

func (s *Student) GetName() string {
	return s.Name
}

func (s *Student) Job() {
	fmt.Println("study..")
}

    //新加一個Teacher的struct
type Teacher struct {
	Id   int
	Name string
}

func (t *Teacher) GetName() string {
	return t.Name
}

func (t *Teacher) Job() {
	fmt.Println("teach...")
}

#代碼分析.net

上一篇只有1個Struct,也就是Student
這裏有2個Struct,一個是Student,另外一個是Teacher。這兩個Struct都實現了STUDENT這個interfacecode

如今注入的時候用ctx.MapTo(s, (*STUDENT)(nil))這個方法,來注入。其中第一個參數s能夠是Student,也能夠是Teacher。第二個參數是一個接口哦,注意。blog

註冊完成後,就能夠用了,就是這句m.Get("/", func(ctx *macaron.Context, s STUDENT),注意的是,這裏是STUDENT,仍是接口。接口

當調用接口上的方法時,s.Job()會知道這個接口背後是哪一個具體類型,若是是Student,就會打印study...,若是是Teacher就會打印teach...get

相關文章
相關標籤/搜索