大漠知秋的加油站

  • 首页
大漠知秋的加油站
你就当我的烂笔头吧
  1. 首页
  2. Golang
  3. 正文

面向对象 - 使用组合和定义别名

2019年1月3日 1198点热度 0人点赞 0条评论

  上一节说过: public 和 private 是针对包一级的可见性,那么如果我们引入了一个其他同事或者第三方的包,有一个功能我们需要使用,但是他们并没有提供,这时候该怎么扩充呢?

使用组合

  如下,有一个第三方提供的加法方法:

package third_partyh

type TMath struct {
    I int
}

func (math *TMath) Add(tarMath TMath) {
    math.I += tarMath.I
}

  我们可以这样使用:

package main

import (
    "exercise/third_party"
    "fmt"
)

func main() {

    a := third_partyh.TMath{10}
    b := third_partyh.TMath{20}

    a.Add(b)
    fmt.Printf("Add:%d", a.I)

}

  后边需要一个 减法功能,但是没有提供,这时候可以使用组合方式来扩展原有结构体。

type MyMath struct {
    TMath *third_partyh.TMath
}

func (math *MyMath) sub(myMath MyMath) {
    if math.TMath == nil || myMath.TMath == nil {
        fmt.Println("TMath is nil")
    }
    math.TMath.I -= myMath.TMath.I
}

  把第三方的实例引用过来,进行扩展。调用:

func main() {

    a := third_partyh.TMath{10}
    b := third_partyh.TMath{20}

    myMathA := MyMath{&a}
    myMathB := MyMath{&b}

    myMathA.sub(myMathB)
    fmt.Printf("Sub:%d", myMathA.TMath.I)

}

定义别名

  这里给 []int,定义别名,自定义一个简单的队列作为样例:

  类型为 slice of int 的队列

package queue

// A FIFO queue.
type Queue []int

// Pushes the element into the queue.
//      e.g. q.Push(123)
func (q *Queue) Push(v int) {
    *q = append(*q, v)
}

// Pops element from head.
func (q *Queue) Pop() int {
    head := (*q)[0]
    *q = (*q)[1:]
    return head
}

// Returns if the queue is empty or not.
func (q *Queue) IsEmpty() bool {
    return len(*q) == 0
}

  调用

func main() {
    q := Queue{1}
    q.Push(2)
    q.Push(3)
    fmt.Println(q.Pop())
    fmt.Println(q.Pop())
    fmt.Println(q.IsEmpty())

    fmt.Println(q.Pop())
    fmt.Println(q.IsEmpty())
}
标签: Golang 定义别名 结构体组合
最后更新:2019年12月26日

大漠知秋

唯黄昏而思烛明,唯覆雪始念日暖,唯放手方知情真,今困苦而怀峥嵘,今飘零而涌乡愁,今孑然而徒唏嘘,唏嘘成愁。

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

文章目录
  • 使用组合
  • 定义别名

COPYRIGHT © 2023 大漠知秋的加油站. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

豫ICP备16029200号-2