type name interface {
funcInterf()
}
type da struct {
name string
sex string
}
type we struct {
addr string
code int
}
func (d *da) funcInterf() {
fmt.Println(d.name, d.sex)
}
func (w *we) funcInterf() {
fmt.Println(w.addr, w.code)
}
//多態(tài)的實現(xiàn)
//接口作為函數(shù)的參數(shù)
func toFunc(n name) {
n.funcInterf()
}
func studyInterf() {
var n name
d := da{"das", "nan"}
n = &d
n.funcInterf()
w := we{"wer", 10086}
//將對象信息賦值給接口類型變量 必須滿足接口方法的聲明格式
//調(diào)用多態(tài)函數(shù)
toFunc(&d)
toFunc(&w)
}
類型斷言
var i interface
i=10
//值胧后,值的判斷:=接口變量.(數(shù)據(jù)類型)
value,ok:i.(int)
面向?qū)ο笥嬎闫鲗崿F(xiàn)
1、方法
2、接口
1、定義接口
type op interface{
Result()int
}
2蜡塌、子類方法
func (a *Add) Result() int{
return a.num1+a.num2
}
3、調(diào)用
a :=Add{}
o=&a
r= o.Result()
3勿负、多態(tài)實現(xiàn)
1馏艾、接口作為參數(shù)
func toFunc(o op ) {
value :=o.Result()
}
2、調(diào)用
toFunc(&a)
4、工廠設(shè)計模式
1琅摩、工廠類信息
type Factory struct{
}
func (f *Factory) Result(num1,num2 int,ch string){
switch ch {
case "+":
var a Add
a.num1=num1
a.num2=num2
toFunc(&a)
}
}
3\調(diào)用
var f Factory
f.Result(10,20,"+")