GO多态实现和接口编程
package main
import "fmt"
//先定义接口 在根据接口实现功能
type Humaner1 interface {
//方法 方法声明
SayHello()
//Result(int, int) int
}
type Student1 struct {
name string
age int
sex string
score int
}
type Teacher1 struct {
name string
age int
sex string
subject string
}
func (s *Student1) SayHello() {
fmt.Printf("大家好,我是%s,我今年%d岁,我是%s生,我的成绩是%d分\n",
s.name, s.age, s.sex, s.score)
}
func (t *Teacher1) SayHello() {
fmt.Printf("大家好,我是%s,我今年%d岁,我是%s生,我的学科是%s\n",
t.name, t.age, t.sex, t.subject)
}
//多态的实现
//将接口作为函数参数 实现多态
func SayHi(h Humaner1){
h.SayHello()
}
func main() {
stu:=Student1{"小明",18,"男",99}
//调用多态函数
SayHi(&stu)
//tea:=Teacher1{"法师",31,"男","go"}
//SayHi(&tea)
}
接口编程综合案例
package main
import "fmt"
//定义接口
type inter interface {
//通信接口
CSocketProtocol()
//加密接口
CEncDesProtocol()
}
//厂商1类
type CSckImp1 struct {
data string
socket string
}
//厂商2类
type CSckImp2 struct {
data string
socket string
value int
}
func (cs1 *CSckImp1) CSocketProtocol() {
fmt.Printf("厂商1的通信接口数据为:%s\n", cs1.socket)
}
func (cs1 *CSckImp1) CEncDesProtocol() {
fmt.Printf("厂商1的加密接口数据为:%s\n", cs1.data)
}
func (cs2 *CSckImp2) CSocketProtocol() {
fmt.Printf("厂商2的通信接口数据为:%s\n", cs2.socket)
}
func (cs2 *CSckImp2) CEncDesProtocol() {
fmt.Printf("厂商2的加密接口数据为:%s 数值为:%d\n", cs2.data,cs2.value)
}
//多态实现
func framework(i inter) {
i.CSocketProtocol()
i.CEncDesProtocol()
}
func main() {
cs1 := CSckImp1{"厂商1的加密数据", "厂商1的通信数据"}
framework(&cs1)
cs2 := CSckImp2{"厂商2的加密数据", "厂商2的通信数据",123}
framework(&cs2)
}
实现多文件 将src目录创建三个文件
main.go文件调取 (运行时在goland中选择目录运行)
//定义接口
type inter interface {
//通信接口
CSocketProtocol()
//加密接口
CEncDesProtocol()
}
//多态实现
func framework(i inter) {
i.CSocketProtocol()
i.CEncDesProtocol()
}
func main() {
cs1 := CSckImp1{"厂商1的加密数据", "厂商1的通信数据"}
framework(&cs1)
cs2 := CSckImp2{"厂商2的加密数据", "厂商2的通信数据",123}
framework(&cs2)
}
厂商1信息.go
package main
import "fmt"
//厂商1类
type CSckImp1 struct {
data string
socket string
}
func (cs1 *CSckImp1) CSocketProtocol() {
fmt.Printf("厂商1的通信接口数据为:%s\n", cs1.socket)
}
func (cs1 *CSckImp1) CEncDesProtocol() {
fmt.Printf("厂商1的加密接口数据为:%s\n", cs1.data)
}
厂商2信息.go
package main
import "fmt"
//厂商2类
type CSckImp2 struct {
data string
socket string
value int
}
func (cs2 *CSckImp2) CSocketProtocol() {
fmt.Printf("厂商2的通信接口数据为:%s\n", cs2.socket)
}
func (cs2 *CSckImp2) CEncDesProtocol() {
fmt.Printf("厂商2的加密接口数据为:%s 数值为:%d\n", cs2.data,cs2.value)
}