一般人思路实现思路如果是oop的思想
package main import "fmt" type Phone interface { call() } type myPhone struct {} func (m myPhone) call(){ fmt.Printf("%s","this is my iphone") } type hwPhone struct {} func (h hwPhone) call(){ fmt.Println("this is hwhone") } func main(){ my:=myPhone{} my.call() hw := hwPhone{} hw.call() }
实现思路:定一个接口,别的结构体实现我对应的方法,如果需要调用,一个结构体一个结构体对象进行调用。思路没有毛病。
思考:如果是框架基础代码。如何更加方便的调用。以为按照上面的方法的话,要写多少结构体。第一:代码的阅读性降低.第二:代码的维护性非常差,操作性不强,所以思考所有的obj对象有没有共同的一个共性,然后抽象出来。所有下面就是多态的实现代码
package main import "fmt" type Persion interface { process() } func Run(persion Persion){ persion.process() } type liming struct {} func (l liming) process(){ fmt.Printf("%s","i am is liming") } type gang struct {} func (g gang) process(){ fmt.Printf("%s","i am is gang") } func main(){ li:=liming{} g:=gang{} dataslice:=make([]Persion,0,1) dataslice = append(dataslice,li) dataslice = append(dataslice,g) for _,val:=range dataslice { Run(val) } }
结论:虽然最后输出的结果都是一样的,都是要实现各自的结构体对象,但是在实际场景中,结构体要实现很多。统一使用Run()方法调用。极大的规范了代码的阅读性和维护性。