面向对象程序设计(Object Oriented Programming,OOP)是一种计算机编程框架,尽可能的模拟人类的思维方式,使得软件的开发方法与过程尽可能接近人类认识世界、解决现实问题的方法和过程。
封装、继承、多态和抽象是面向对象的4个基本特征。
type Person struct {
name string
age int
}
func NewPerson() Person {
return Person{}
}
func (this *Person) SetName(name string) {
this.name = name
}
func (this *Person) GetName() string {
return this.name
}
func (this *Person) SetAge(age int) {
this.age = age
}
func (this *Person) GetAge() string {
return this.age
}
func main() {
p := NewPerson()
p.SetName("xiaofei")
fmt.Println(p.GetName())
}
type Student struct {
Person
StuId int
}
func (this *Student) SetId(id int) {
this.StuId = id
}
func (this *Student) GetId() int {
return this.StuId
}
func main() {
stu := oop.Student{}
stu.SetName("xiaofei") // 可以直接访问Person的Set、Get方法
stu.SetAge(22)
stu.SetId(123)
fmt.Printf("I am a student,My name is %s, my age is %d, my id is %d", stu.GetName(), stu.GetAge(), stu.GetId)
}
将共同的属性和方法抽象出来形成一个不可以被实例化的类型,由于抽象和多态是相辅相成的,或者说抽象的目的就是为了实现多态。
// 小狗和小鸟都是动物,都会移动和叫,它们共同的方法就可以提炼出来定义为一个抽象的接口。
type Animal interface {
Move()
Shout()
}
type Dog struct {
}
func (dog Dog) Move() {
fmt.Println("I am dog, I moved by 4 legs.")
}
func (dog Dog) Shout() {
fmt.Println("WANG WANG WANG")
}
type Bird struct {
}
func (bird Bird) Move() {
fmt.Println("I am bird, I fly with 2 wings")
}
func (bird Bird) Shout() {
fmt.Println("ji ji ji ")
}
type ShowAnimal struct {
}
func (s ShowAnimal) Show(animal Animal) {
animal.Move()
animal.Shout()
}
func main() {
show := ShowAnimal{}
dog := Dog{}
bird := Bird{}
show.Show(dog)
show.Show(bird)
}
参考资料:
原文:https://www.cnblogs.com/xiaofeidu/p/14944859.html