接口

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,"+")
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容