type tester interface {test()string() string}type data struct {}func (*data) test() {}func (data) string() string {return ""}func main() {var d data// var t tester = d // 错误:test()不属于data的方法集,所以不支持转换var t tester = &d // 结构类型是可以直接转换为接口类型t.test()println(t.string())}
type stringer interface {string() string}type tester interface {stringer // 嵌入stringer接口tester()}type data struct {}func (*data) test() {}func (data) string() string {return ""}func pp(a stringer) { // 超级接口变量,可以隐式转换为子集,反过来不行println(a.string())}func main() {var d datavar t tester = &d // *data包含tester所有的方法集,实现了tester接口pp(t) // 隐式转换为接口子集stringervar s stringer = t // 显示转换为接口子集stringerprintln(s.string())// var t2 tester = s // 接口不能逆向转换}
type Pet interface {Name() string}type Dog struct {Language() string}type Cat struct {Color() string}func (d Dog) Name() string {return "Dog"}func (d Dog) Language() string {return "汪汪汪"}func (d Cat) Name() string {return "Cat"}func (d Cat) Color() string {return "Black"}func main() {var p petvar dog1 Dogvar cat1 Catpet = dog1 // 动态类型为Dogprintln(pet.Name()) // 输出:Dog,其实调用的是dog.Name()pet = cat1 // 动态类型为Catprintln(pet.Name()) // 输出:Cat,其实调用的是cat.Name()pet = nil // 动态类型和值都是nil}
type Interface interface {Len() intLess(i, j int) boolSwap(i, j int)}type reverse struct {Interface}
type Interface interface {Len() intLess(i, j int) boolSwap(i, j int)}// Array 实现Interface接口type Array []intfunc (arr Array) Len() int {return len(arr)}func (arr Array) Less(i, j int) bool {return arr[i] < arr[j]}func (arr Array) Swap(i, j int) {arr[i], arr[j] = arr[j], arr[i]}// 匿名接口(anonymous interface)type reverse struct {Interface}// 重写(override)func (r reverse) Less(i, j int) bool {return r.Interface.Less(j, i)}// 构造reverse Interfacefunc Reverse(data Interface) Interface {return &reverse{data}}func main() {arr := Array{1, 2, 3}rarr := Reverse(arr)fmt.Println(arr.Less(0,1))fmt.Println(rarr.Less(0,1))}
// 同上,全部省略。。。// 匿名structtype reverse struct {Array}// 重写func (r reverse) Less(i, j int) bool {return r.Array.Less(j, i)}// 构造reverse Interfacefunc Reverse(data Array) Interface {return &reverse{data}}func main() {arr := Array{1, 2, 3}rarr := Reverse(arr)fmt.Println(arr.Less(0, 1))fmt.Println(rarr.Less(0, 1))}
不依赖具体实现:即接口为A,结构体B1、B2实现了接口A,结构体C内嵌了A,那么C.A可以通过B1/B2实例化;
对接口类型进行重写:当C.A通过B1实例化后,C和B1的关系,可以转变为接口体C内嵌结构体B1,那么C可以直接使用B1中的所有方法,当然C也可以对B1中的方法进行重写,这里官方文档这样解释“Interface and we can override a specific method without having to define all the others.”
type IMessage interface {Print()}type BaseMessage struct {//IMessage 没有必要embedding这个interface,因为只是按照契约实现接口,但是并没有利用接口的数据和功能//一般说来直接实现接口的类都没有必要embedding接口msg string}func (message *BaseMessage) Print() {fmt.Println("baseMessage:", message.msg)}type SubMessage struct {BaseMessage //因为要使用BaseMessage的数据,所以必须embedding}func (message *SubMessage) Print() {fmt.Println("subMessage:", message.msg)}func interface_use(i IMessage) {i.Print()}func main() {baseMessage := new(BaseMessage)baseMessage.msg = "a"interface_use(baseMessage) // 输出:baseMessage:aSubMessage := new(SubMessage)SubMessage.msg = "b"interface_use(SubMessage) // 输出:subMessage:b}
实现接口:结构体BaseMessage,实现了IMessage接口的所有方法;
匿名字段嵌入 + 方法覆盖:结构体SubMessage嵌入了BaseMessage,也实现了自己的Print(),所以实际使用时,SubMessage.Print()会覆盖BaseMessage.Print();
接口转换:BaseMessage和SubMessage可以转换为IMessage接口,代码里面是隐式转换;
动态类型:BaseMessage和SubMessage都实现了IMessage接口,所以通过隐式转换后,IMessage接口的动态类型和动态值会相应改变,当动态类型为BaseMessage时,执行i.Print(),执行的是BaseMessage.Print();当动态类型为SubMessage,执行i.Print(),执行的是SubMessage.Print()。
// Context 上下文type Context struct{}// Component 组件接口type Component interface {Mount(c Component, components ...Component) error // 添加一个子组件Remove(c Component) error // 移除一个子组件Do(ctx *Context) error // 执行组件&子组件}// BaseComponent 基础组件// 实现Add:添加一个子组件// 实现Remove:移除一个子组件type BaseComponent struct {ChildComponents []Component // 子组件列表}// Mount 挂载一个子组件func (bc *BaseComponent) Mount(c Component, components ...Component) (err error) {bc.ChildComponents = append(bc.ChildComponents, c)if len(components) == 0 {return}bc.ChildComponents = append(bc.ChildComponents, components...)return}// Remove 移除一个子组件func (bc *BaseComponent) Remove(c Component) (err error) {if len(bc.ChildComponents) == 0 {return}for k, childComponent := range bc.ChildComponents {if c == childComponent {fmt.Println(runFuncName(), "移除:", reflect.TypeOf(childComponent))bc.ChildComponents = append(bc.ChildComponents[:k], bc.ChildComponents[k+1:]...)}}return}// Do 执行组件&子组件func (bc *BaseComponent) Do(ctx *Context) (err error) {// do nothingreturn}// ChildsDo 执行子组件func (bc *BaseComponent) ChildsDo(ctx *Context) (err error) {// 执行子组件for _, childComponent := range bc.ChildComponents {if err = childComponent.Do(ctx); err != nil {return err}}return}// CheckoutPageComponent 订单结算页面组件type CheckoutPageComponent struct {// 合成复用基础组件BaseComponent}// Do 执行组件&子组件func (bc *CheckoutPageComponent) Do(ctx *Context) (err error) {// 当前组件的业务逻辑写这fmt.Println(runFuncName(), "订单结算页面组件...")// 执行子组件bc.ChildsDo(ctx)// 当前组件的业务逻辑写这return}// AddressComponent 地址组件type AddressComponent struct {BaseComponent}func (bc *AddressComponent) Do(ctx *Context) (err error) {fmt.Println(runFuncName(), "地址组件...")bc.ChildsDo(ctx)return}// StoreComponent 店铺组件type StoreComponent struct {BaseComponent}func (bc *StoreComponent) Do(ctx *Context) (err error) {fmt.Println(runFuncName(), "店铺组件...")bc.ChildsDo(ctx)return}// SkuComponent 商品组件type SkuComponent struct {BaseComponent}func (bc *SkuComponent) Do(ctx *Context) (err error) {fmt.Println(runFuncName(), "商品组件...")bc.ChildsDo(ctx)return}// PromotionComponent 优惠信息组件type PromotionComponent struct {BaseComponent}func (bc *PromotionComponent) Do(ctx *Context) (err error) {fmt.Println(runFuncName(), "优惠信息组件...")bc.ChildsDo(ctx)return}// ExpressComponent 物流组件type ExpressComponent struct {BaseComponent}func (bc *ExpressComponent) Do(ctx *Context) (err error) {fmt.Println(runFuncName(), "物流组件...")bc.ChildsDo(ctx)return}// AftersaleComponent 售后组件type AftersaleComponent struct {BaseComponent}func (bc *AftersaleComponent) Do(ctx *Context) (err error) {fmt.Println(runFuncName(), "售后组件...")bc.ChildsDo(ctx)return}func main() {// 初始化订单结算页面 这个大组件checkoutPage := &CheckoutPageComponent{}// 挂载子组件storeComponent := &StoreComponent{}skuComponent := &SkuComponent{}skuComponent.Mount(&PromotionComponent{},&AftersaleComponent{},)storeComponent.Mount(skuComponent,&ExpressComponent{},)// 挂载组件checkoutPage.Mount(&AddressComponent{},storeComponent,)// 开始构建页面组件数据checkoutPage.Do(&Context{})}
type Pool interface {Get() (io.Closer, error)Put(obj io.Closer)Close() error}// 工厂方法func NewPool(type, name string, size int, newFunc func() (io.Closer, error)) Pool {if type == "chanPool" {return NewChanPool(name, size, newFunc)} else {return NewRingBufferPool(name, size, newFunc)}}//type chanPool struct {name stringsize intidle int32max int32ch chan io.Closernew func() (io.Closer, error)}func NewChanPool(name string, size int, newFunc func() (io.Closer, error)) Pool {return &chanPool{name: name,size: size,ch: make(chan io.Closer, size),new: newFunc,}}// 假如实现了Pool接口,实现方法省略。。。type ringBufferPool struct {sync.Onceerr errorclosed int32name stringrb *RingBuffernew func() (io.Closer, error)}func NewRingBufferPool(name string, size int, newFunc func() (io.Closer, error)) Pool {return &ringBufferPool{err: errors.New("failed get object from ring buffer pool " + name),name: name,rb: NewRingBuffer(int32(size)),new: newFunc,}}// 实现了Pool接口,实现方法省略。。。func main() {var poolpool := NewPool("chanPool", "testpool", 10, nil)pool.Close() // 调用的是chanPool的Close方法pool := NewPool("ringBufferPool", "testpool", 10, nil)pool.Close() // 调用的是ringBufferPool的Close方法}