学习面向对象之前,应该搞清楚,什么是面向对象?为什么用面向对象?以及使用面向对象有什么优缺点?不了解的同学可以找google 或baidu,此篇不再赘述。
go 没有对象(object)、类(class)等面向对象概念,但提供了struct,interface等特性实现类似的功能。面向对象有三大特性:封装、继承、多态,接下来我们看看go语言是怎么处理的。
封装
struct是一种包含了命名域和方法的类型
例子
package main
import "fmt"
type Animal struct {
Age int32
Type string
}
func (a *Animal) GetAge() int32 {
return a.Age
}
func main() {
a := Animal{Age: 18}
fmt.Println(a.GetAge())
}
上面的例子定义了一个Animal 的struct类型, 该struct含有int32,和string类型的域;
同时Animal 上绑定了一个GetAge方法。
当然我们也可以从广义上将包(package)理解为一个封装。
方法、结构、变量、常量等,针对包的范围。
首字母大写代表 public
首字母小写代表 pirvate
继承
例子
package main
import "fmt"
type Animal struct {
Age int32
Type string
}
type Dog struct {
Animal
}
func (a *Animal) GetAge() int32 {
return a.Age
}
func main() {
a := Dog{}
a.Age=18
fmt.Println(a.GetAge())
}
代码中Dog 的struct继承了Animal 所有的类型和方法
多态
这里我们需要借助interface类型
package main
import "fmt"
type Animal interface {
GetAge() int32
GetType() string
}
type Cat struct {
Age int32
Type string
}
type Dog struct {
Age int32
Type string
}
func (a *Dog) GetAge() int32 {
return a.Age
}
func (a *Dog) GetType() string {
return a.Type
}
func (c *Cat) GetAge() int32 {
return c.Age
}
func (c *Cat) GetType() string {
return c.Type
}
func Factory(name string) Animal {
switch name {
case "dog":
return &Dog{Age: 20, Type: "DOG"}
case "cat":
return &Cat{Age: 20, Type: "CAT"}
default:
panic("No such animal")
}
}
func main() {
animal := Factory("dog")
fmt.Println()
fmt.Printf("%s max age is: %d", animal.GetType(), animal.GetAge())
animal = Factory("cat")
fmt.Printf("%s max age is: %d", animal.GetType(), animal.GetAge())
}
结果
DOG max age is: 20CAT max age is: 20
凡是实现了Animal 接口类所有的方法,如 Cat, Dog实现了Animal中的全部方法。它就被认为是Animal 接口类的子类。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。