您的位置:首页 > 编程语言 > Go语言

go的interface示例实现多态范式

2018-11-09 21:35 393 查看
版权声明:本文为博主原创文章,转载时请务必注明本文地址, 禁止用于任何商业用途, 否则会用法律维权。 https://blog.csdn.net/stpeace/article/details/83868186

        看程序:

[code]package main
import "fmt"

type BaseIntf interface {
Process()
}

type Msg1 struct {
req int
rsp int
}

func (p *Msg1) Process()  {
fmt.Println("process 1")
}

type Msg2 struct {
req int
rsp int
}

func (p *Msg2) Process()  {
fmt.Println("process 2")
}

func main() {
m1 := new(Msg1)
m1.Process()

m2 := new(Msg2)
m2.Process()
}

        变一下:

[code]package main
import "fmt"

type BaseIntf interface {
Process()
}

func Run(proc BaseIntf) {
fmt.Println("run")
proc.Process()
}

type Msg1 struct {
req int
rsp int
}

func (p *Msg1) Process()  {
fmt.Println("process 1")
}

type Msg2 struct {
req int
rsp int
}

func (p *Msg2) Process()  {
fmt.Println("process 2")
}

func main() {
m1 := new(Msg1)
Run(m1)

m2 := new(Msg2)
Run(m2)
}

         这种风格的代码,见了很多次了。

         不多说。

 

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: