一文详解Go的面向对象编程

概述

  • Go 语言的面向对象编程有三个重要的思想:封装、继承和多态。
  • 封装

Go 语言通过 struct 结构体的方式来实现封装,结构体可以包含各种类型的变量和方法,可以将一组相关的变量和方法封装在一起。使用首字母大小写控制变量和方法的访问权限,实现了信息隐藏和访问控制。

  • 继承

Go 语言中没有传统的继承机制,但是可以使用嵌入式类型来实现类似继承的效果,将一个类型嵌入到另一个类型中,从而继承嵌入类型的方法和属性。嵌入式类型的特点是可以直接访问嵌入类型的属性和方法,不需要通过接口或者其他方式进行转换。在 Go 语言中,可以通过 struct 嵌套和 interface 嵌套来实现继承的效果。

  • 多态

Go 语言通过接口来实现多态,一个类型只需要实现了接口的所有方法,就可以被赋值给该接口类型的变量。这样可以实现类似于面向对象语言中的多态性。多态性使得程序可以根据上下文环境自动选择合适的方法实现,提高了代码的灵活性和可复用性。

实战

常规函数写法

在这个示例中,函数和结构体是分离的,函数接收结构体指针类型作为参数,需要手动传递结构体的指针。尽管这种方式有一定的缺陷,调用会比较麻烦,但它更加符合基于过程式编程思想的设计理念,即将一个大问题拆分成多个小问题,并通过函数解决这些小问题。适用于初学者对于代码的简单操作。优点就只有易于理解。

  1. package test
  2.  
  3. import (
  4.      “fmt”
  5.      “testing”
  6. )
  7.  
  8. type Mobile struct {
  9.      User string `json:”user”`
  10.      Brand string `json:”brand”`
  11.      Prise float64 `json:”prise”`
  12. }
  13.  
  14. func CallUp(*Mobile) {
  15.      fmt.Printf(“%s is using %.2f mobile phone to make a call.\n”, m.User, m.Prise)
  16. }
  17.  
  18. func Storage(*Mobile) {
  19.      fmt.Printf(“%s is using a %s mobile phone to transfer data.\n”, m.User, m.Brand)
  20. }
  21.  
  22. func Charge(*Mobile) string {
  23.      return fmt.Sprintf(“%s is charging a %s phone.\n”, m.User, m.Brand)
  24. }
  25.  
  26. func Game(*Mobile, name string) {
  27.      fmt.Printf(“%s is playing the game of ‘%s’.\n”, m.User, name)
  28. }
  29.  
  30. func TestExample(*testing.T) {
  31.      iPhone := Mobile{
  32.          User: “Tom”,
  33.          Brand: “iPhone 15 Pro MAX”,
  34.          Prise: 12688.00,
  35.      }
  36.      CallUp(&iPhone)
  37.      Game(&iPhone, “Card”)
  38.      Storage(&iPhone)
  39.      fmt.Printf(Charge(&iPhone))
  40. }

调用结构体类型上的方法

调用结构体类型上的方法体现了面向对象编程的封装思想。封装的核心是将数据和行为打包在一起,通过公开和私有的方式来隐藏实现细节。这样可以使得代码更加模块化、安全、易于维护,并且更加符合现实世界中的抽象模型。

相比于上面的函数调用,调用结构体类型上的方法可以使调用方法时不必手动传递结构体实例对象,只需聚焦于方法参数本身,提高了代码的可读性和易用性。这也符合面向对象编程的简洁性和代码重用性的思想。

提示:在代码注释中类比了 python 中类的写法。

  1. package test
  2.  
  3. import (
  4.      “fmt”
  5.      “testing”
  6. )
  7.  
  8. // class Mobile(object)
  9. type Mobile struct {
  10.      User string `json:”user”`
  11.      Brand string `json:”brand”`
  12.      Prise float64 `json:”prise”`
  13. }
  14.  
  15. // def __init__(user, brand, prise)
  16. func NewMobile(user string, brand string, prise float64) *Mobile {
  17.      return &Mobile{User: user, Brand: brand, Prise: prise}
  18. }
  19.  
  20. // def call_up(self)
  21. func (*Mobile) CallUp() {
  22.      fmt.Printf(“%s is using %.2f mobile phone to make a call.\n”, m.User, m.Prise)
  23. }
  24.  
  25. // def storage(self)
  26. func (*Mobile) Storage() {
  27.      fmt.Printf(“%s is using a %s mobile phone to transfer data.\n”, m.User, m.Brand)
  28. }
  29.  
  30. // def charge(self)
  31. func (*Mobile) Charge() string {
  32.      return fmt.Sprintf(“%s is charging a %s phone.\n”, m.User, m.Brand)
  33. }
  34.  
  35. // def game(self, name)
  36. func (*Mobile) Game(name string) {
  37.      fmt.Printf(“%s is playing the game of ‘%s’.\n”, m.User, name)
  38. }
  39.  
  40. func TestExample(*testing.T) {
  41.      applePhone := NewMobile(“Tom”, “iPhone 15 Pro MAX”, 12688.00)
  42.      applePhone.CallUp()
  43.      applePhone.Game(“Card”)
  44.      applePhone.Storage()
  45.      fmt.Printf(applePhone.Charge())
  46. }

调用接口类型上的方法

接口实例: 是指定义一个接口类型,并将具体的结构体类型的实例传递给它。

调用接口类型上的方法,将接口与结构体类型分开,使接口具有更广泛的适用性。使用 “接口实例” 可以实现更灵活的代码设计,因为可以在运行时动态地选择要使用的实现类型。

同时,由于接口只关心方法的签名,而不关心具体实现方式,因此可以将不同的结构体类型传递给同一个接口,从而实现面向对象思想的多态性。

在这个示例中,定义了一个 USB 接口和 PlayBoy 接口,它们都包含各自的方法。在测试函数中调用这两个接口的方法时需要分别调用。这两个接口之间没有直接的联系或关联,它们是相互独立的。如果你想将这两个接口组合在一起,可以使用 “嵌入式接口”。

  1. package test
  2.  
  3. import (
  4.      “fmt”
  5.      “testing”
  6. )
  7.  
  8. var (
  9.      applePhone, huaweiPhone *Mobile
  10. )
  11.  
  12. func init() {
  13.      applePhone = NewMobile(“Tom”, “iPhone 15 Pro MAX”, 12688.00)
  14.      huaweiPhone = NewMobile(“John”, “Huawei Meta 40 Pro”, 8888.00)
  15. }
  16.  
  17. type USB interface {
  18.      Storage()
  19.      Charge() string
  20. }
  21.  
  22. type PlayBoy interface {
  23.      Game(name string)
  24. }
  25.  
  26. type Mobile struct {
  27.      User string `json:”user”`
  28.      Brand string `json:”brand”`
  29.      Prise float64 `json:”prise”`
  30. }
  31.  
  32. func NewMobile(user string, brand string, prise float64) *Mobile {
  33.      return &Mobile{User: user, Brand: brand, Prise: prise}
  34. }
  35.  
  36. func (*Mobile) CallUp() {
  37.      fmt.Printf(“%s is using %.2f mobile phone to make a call.\n”, m.User, m.Prise)
  38. }
  39.  
  40. func (*Mobile) Storage() {
  41.      fmt.Printf(“%s is using a %s mobile phone to transfer data.\n”, m.User, m.Brand)
  42. }
  43.  
  44. func (*Mobile) Charge() string {
  45.      return fmt.Sprintf(“%s is charging a %s phone.\n”, m.User, m.Brand)
  46. }
  47.  
  48. func (*Mobile) Game(name string) {
  49.      fmt.Printf(“%s is playing the game of ‘%s’.\n”, m.User, name)
  50. }
  51.  
  52. func TestExample(*testing.T) {
  53.      USB.Storage(applePhone)
  54.      fmt.Printf(USB.Charge(huaweiPhone))
  55.      PlayBoy.Game(huaweiPhone, “LOL”)
  56. }

嵌入式接口

嵌入式接口: 是一种将一个接口嵌入到另一个接口中的技术,嵌入的接口中的所有方法都会被继承到当前接口中。通过接口的嵌套,可以将多个接口组合成一个更大的接口,从而使代码更加简洁、灵活。这也体现了面向对象编程中的继承特性。

在这个示例中,定义了一个 IPhone 接口,它嵌入了 USB 接口和 PlayBoy 接口,以及 CallUp() 方法。 从而可以使用这三个接口中的所有方法。通过这种方式,我们可以将不同的接口组合成一个更大的接口,以便更方便地使用这些方法。在测试函数中,我们创建了一个 Mobile 类型的实例,并将其转换为 IPhone 类型的接口实例 p,然后可以使用 p 调用 Mobile 结构体中实现的 CallUp()Game()Storage() 和 Charge() 方法。

  1. package test
  2.  
  3. import (
  4.      “fmt”
  5.      “testing”
  6. )
  7.  
  8. type IPhone interface {
  9.      USB
  10.      PlayBoy
  11.      CallUp()
  12. }
  13.  
  14. type USB interface {
  15.      Storage()
  16.      Charge() string
  17. }
  18.  
  19. type PlayBoy interface {
  20.      Game(name string)
  21. }
  22.  
  23. type Mobile struct {
  24.      User string `json:”user”`
  25.      Brand string `json:”brand”`
  26.      Prise float64 `json:”prise”`
  27. }
  28.  
  29. func (*Mobile) CallUp() {
  30.      fmt.Printf(“%s is using %.2f mobile phone to make a call.\n”, m.User, m.Prise)
  31. }
  32.  
  33. func (*Mobile) Storage() {
  34.      fmt.Printf(“%s is using a %s mobile phone to transfer data.\n”, m.User, m.Brand)
  35. }
  36.  
  37. func (*Mobile) Charge() string {
  38.      return fmt.Sprintf(“%s is charging a %s phone.\n”, m.User, m.Brand)
  39. }
  40.  
  41. func (*Mobile) Game(name string) {
  42.      fmt.Printf(“%s is playing the game of ‘%s’.\n”, m.User, name)
  43. }
  44.  
  45. func TestExample(*testing.T) {
  46.      newMobile := &Mobile{User: “John”, Brand: “Huawei Meta 40 Pro”, Prise: 8888.00}
  47.      var p IPhone = newMobile
  48.      p.CallUp()
  49.      p.Game(“Card”)
  50.      p.Storage()
  51.      fmt.Printf(p.Charge())
  52. }

 

到此这篇关于一文详解Go的面向对象编程的文章就介绍到这了,更多相关Go面向对象内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

标签

发表评论