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)
}
//多态的实现
//接口作为函数的参数
func toFunc(n name) {
n.funcInterf()
}
func studyInterf() {
var n name
d := da{"das", "nan"}
n = &d
n.funcInterf()
w := we{"wer", 10086}
//将对象信息赋值给接口类型变量 必须满足接口方法的声明格式
//调用多态函数
toFunc(&d)
toFunc(&w)
}
类型断言
var i interface
i=10
//值,值的判断:=接口变量.(数据类型)
value,ok:i.(int)
面向对象计算器实现
1、方法
2、接口
1、定义接口
type op interface{
Result()int
}
2、子类方法
func (a *Add) Result() int{
return a.num1+a.num2
}
3、调用
a :=Add{}
o=&a
r= o.Result()
3、多态实现
1、接口作为参数
func toFunc(o op ) {
value :=o.Result()
}
2、调用
toFunc(&a)
4、工厂设计模式
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\调用
var f Factory
f.Result(10,20,"+")
网友评论