go笔记:go语言继承和简易工厂 1、先定义接口type OVSCreater interface{ SetCmd error }接口用er结尾2、定义一个结构体type OVSBridge struct{ bridgeProfile conf.BridgeProfile }这里面包含了所需要的数据。3、定义构造函数func NewOvsBridge(element []byte) *OVSBridge{ bridge := new(OVSBridge) //使用入参为bridge赋值,进行构造 //do sth return bridge }构造函数以New开头,返回结构体的实例4、实现接口中的函数func(bridge OVSBridge) SetCmd() error{ err := dosth(bridge.bridgeProfile) if err!=nil{ //dosth } return err }5、建立简易工厂func OVSCreateFactory(resType string,element []byte) OVSCreater { if resType == "NetBridge" { return NewOvsBridge(element) } return nil }工厂返回的是接口类型6、使用var instance OVSCreater instance = OVSCreateFactory(intype,element) instance.SetCmd()//调用类函数执行操作,instance为接口,可以抽象出更大的空间 来自 大脸猫 写于 2015-08-23 10:59 -- 更新于2020-10-19 13:06 -- 2 条评论