likes
comments
collection
share

Go 的面向对象编程技巧

作者站长头像
站长
· 阅读数 23

从 Struct 到 Interface 方法的进阶

可以遗憾,但不要后悔。 

我们留在这里,从来不是身不由己。 

——— 而是选择在这里经历生活

目录

本文主要围绕 GolangObject-oriented 所展开,介绍了其基本的面向对象的基本概念及代码实战。

  1. 概述
  2. 代码实战
  3. 调用对比

概述

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

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

  1. 继承

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

  1. 多态

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

代码实战

常规函数写法

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

package test

import (
    "fmt"
    "testing"
)

type Mobile struct {
    User  string  `json:"user"`
    Brand string  `json:"brand"`
    Prise float64 `json:"prise"`
}

func CallUp(m *Mobile) {
    fmt.Printf("%s is using 💲%.2f mobile phone to make a call.\n", m.User, m.Prise)
}

func Storage(m *Mobile) {
    fmt.Printf("%s is using a %s mobile phone to transfer data.\n", m.User, m.Brand)
}

func Charge(m *Mobile) string {
    return fmt.Sprintf("%s is charging a %s phone.\n", m.User, m.Brand)
}

func Game(m *Mobile, name string) {
    fmt.Printf("%s is playing the game of '%s'.\n", m.User, name)
}

func TestExample(t *testing.T) {
    iPhone := Mobile{
        User:  "Tom",
        Brand: "iPhone 15 Pro MAX",
        Prise: 12688.00,
    }
    CallUp(&iPhone)
    Game(&iPhone, "Card")
    Storage(&iPhone)
    fmt.Printf(Charge(&iPhone))
}

调用结构体类型上的方法

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

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

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

package test

import (
    "fmt"
    "testing"
)

// class Mobile(object)
type Mobile struct {
    User  string  `json:"user"`
    Brand string  `json:"brand"`
    Prise float64 `json:"prise"`
}

// def __init__(user, brand, prise)
func NewMobile(user string, brand string, prise float64) *Mobile {
    return &Mobile{User: user, Brand: brand, Prise: prise}
}

// def call_up(self)
func (m *Mobile) CallUp() {
    fmt.Printf("%s is using 💲%.2f mobile phone to make a call.\n", m.User, m.Prise)
}

// def storage(self)
func (m *Mobile) Storage() {
    fmt.Printf("%s is using a %s mobile phone to transfer data.\n", m.User, m.Brand)
}

// def charge(self)
func (m *Mobile) Charge() string {
    return fmt.Sprintf("%s is charging a %s phone.\n", m.User, m.Brand)
}

// def game(self, name)
func (m *Mobile) Game(name string) {
    fmt.Printf("%s is playing the game of '%s'.\n", m.User, name)
}

func TestExample(t *testing.T) {
    applePhone := NewMobile("Tom", "iPhone 15 Pro MAX", 12688.00)
    applePhone.CallUp()
    applePhone.Game("Card")
    applePhone.Storage()
    fmt.Printf(applePhone.Charge())
}

调用接口类型上的方法

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

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

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

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

package test

import (
    "fmt"
    "testing"
)

var (
    applePhone, huaweiPhone *Mobile
)

func init() {
    applePhone = NewMobile("Tom", "iPhone 15 Pro MAX", 12688.00)
    huaweiPhone = NewMobile("John", "Huawei Meta 40 Pro", 8888.00)
}

type USB interface {
    Storage()
    Charge() string
}

type PlayBoy interface {
    Game(name string)
}

type Mobile struct {
    User  string  `json:"user"`
    Brand string  `json:"brand"`
    Prise float64 `json:"prise"`
}

func NewMobile(user string, brand string, prise float64) *Mobile {
    return &Mobile{User: user, Brand: brand, Prise: prise}
}

func (m *Mobile) CallUp() {
    fmt.Printf("%s is using 💲%.2f mobile phone to make a call.\n", m.User, m.Prise)
}

func (m *Mobile) Storage() {
    fmt.Printf("%s is using a %s mobile phone to transfer data.\n", m.User, m.Brand)
}

func (m *Mobile) Charge() string {
    return fmt.Sprintf("%s is charging a %s phone.\n", m.User, m.Brand)
}

func (m *Mobile) Game(name string) {
    fmt.Printf("%s is playing the game of '%s'.\n", m.User, name)
}

func TestExample(t *testing.T) {
    USB.Storage(applePhone)
    fmt.Printf(USB.Charge(huaweiPhone))
    PlayBoy.Game(huaweiPhone, "LOL")
}

嵌入式接口

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

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

package test

import (
    "fmt"
    "testing"
)

type IPhone interface {
    USB
    PlayBoy
    CallUp()
}

type USB interface {
    Storage()
    Charge() string
}

type PlayBoy interface {
    Game(name string)
}

type Mobile struct {
    User  string  `json:"user"`
    Brand string  `json:"brand"`
    Prise float64 `json:"prise"`
}

func (m *Mobile) CallUp() {
    fmt.Printf("%s is using 💲%.2f mobile phone to make a call.\n", m.User, m.Prise)
}

func (m *Mobile) Storage() {
    fmt.Printf("%s is using a %s mobile phone to transfer data.\n", m.User, m.Brand)
}

func (m *Mobile) Charge() string {
    return fmt.Sprintf("%s is charging a %s phone.\n", m.User, m.Brand)
}

func (m *Mobile) Game(name string) {
    fmt.Printf("%s is playing the game of '%s'.\n", m.User, name)
}

func TestExample(t *testing.T) {
    newMobile := &Mobile{User: "John", Brand: "Huawei Meta 40 Pro", Prise: 8888.00}
    var p IPhone = newMobile
    p.CallUp()
    p.Game("Card")
    p.Storage()
    fmt.Printf(p.Charge())
}

调用对比

代码示例:

package test

import (
    "fmt"
    "testing"
)

type IO interface {
    Reader() IO
    Writer(string) IO
}

type Disk struct {
    storage string
}

func (d *Disk) Reader() IO {
    fmt.Println(d.storage)
    return d
}

func (d *Disk) Writer(s string) IO {
    d.storage = s
    return d
}

func TestExample(t *testing.T) {
    disk := Disk{
        storage: "Hi Bro~",
    }

    // 方式1
    fmt.Println(disk.storage)

    // 方式2
    disk.Writer("Bonjour").Reader()

    // 方式3
    IO(&disk).Writer("Hola").Reader()

    // 方式4
    IO.Writer(&disk, "What's up, man?").Reader()

    // 补充
    var io IO = &disk // 创建了interface变量,并将其赋值为指向Disk类型的指针
    io.Writer("你好").Reader()

    // 总之,以上几种方式实现的效果是相同的,但它们的语法和用法略有不同。
}

方式对比:

序号代码描述
方式1fmt.Println(disk.storage)直接打印struct实例的属性值(私有不建议直接使用)。
方式2disk.Writer("xxx").Reader() 使用原生struct上绑定的方法,链式调用,将多个操作连接在一起,代码比较简洁。
方式3IO(&disk).Writer("xxx").Reader()通过将struct实例转换成接口类型来调用接口方法,适用于需要使用不同的实现类型来满足接口方法的情况,同样使用了方法链的方式,代码较为直观。
方式4IO.Writer(&disk, "xxx").Reader() 直接调用接口类型的方法,传递实现类型的struct实例作为第一个参数传入,同样使用了方法链的方式,代码看起来也很简单。

💡 除了方式1某些场景下不建议,方式2-4这三种方式都可以使用,具体选择哪一种方式取决于个人的编码习惯和项目要求,可根据实际需求进行选择。

转载自:https://juejin.cn/post/7226210789376196666
评论
请登录