go筆記:go語言繼承和簡易工廠
- 2019 年 11 月 22 日
- 筆記
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為介面,可以抽象出更大的空間