设计模式之接口简介
GO语言并非典型的面向对象语言,没有类(class)\继承(extend)\实现(implements)等关键字.
GO语言 通过 struct 关键字实现 面向对象语言里 class 的效果
Go 语言 提供了数据类型 interface{},所有的类型或 struct 默认实现了interface{}.
Go 语言通过自定义interface{},把所有的具有共性的方法定义在一起,任何其他类型只要实现了这些方法就是实现了这个接口。
代码示例:
/* 定义接口 */
type interface_name interface {
method_name1 [return_type]
method_name2 [return_type]
method_name3 [return_type]
...
}
/* 定义结构体 */
type struct_name struct {
/* variables */
}
/* 实现接口方法 */
func (struct_name_variable struct_name) method_name1() [return_type] {
/* 方法实现 */
}
...
代码示例:
package main
import (
"fmt"
)
/** 定义电话接口 **/
type Phone interface {
call()
}
type NokiaPhone struct {
}
// NokiaPhone 实现了 call 方法,因此 NokiaPhone实现了 Phone 接口
func (nokiaPhone NokiaPhone) call() {
fmt.Println("I am Nokia, I can call you!")
}
type IPhone struct {
}
func (iPhone IPhone) call() {
fmt.Println("I am iPhone, I can call you!")
}
func main() {
var phone Phone
phone = new(NokiaPhone)
phone.call()
phone = new(IPhone)
phone.call()
}