golang 面向对象

一 对象封装

package main

import "fmt"

type Phone0 struct {
	number  string
	color string
}
func (p Phone0) Dial() {
	fmt.Printf("Dail from %s ; color is %s\n", p.number, p.color)
}

func (p *Phone0) Init(number string, color string) {
	p.number = number
	p.color = color
}

func main(){
	p := Phone0{}
	p.Init("187********", "white")
	p.Dial()

	p.color = "black"
	p.Dial()
}

  

二 继承

package main

import "fmt"

type Phone1 struct {
    number string
}

func (p *Phone1) Init(number string) {
    p.number = number
}

func (p Phone1) Dial() {
    fmt.Printf("Dail from %s \n", p.number)
}

type Xiaomi struct {
    Phone1
    dtype string
}

func (x *Xiaomi) Init(number string, dtype string) {
    x.Phone1.Init(number)
    x.dtype = dtype
}

func (x Xiaomi) DialXiaomi() {
    fmt.Printf("Dail from %s, type is %s \n", x.number, x.dtype)
}


func main() {
    p := Phone1{}
    p.Init("135********")
    p.Dial()

    e := Xiaomi{}
    e.Init("138********", "xiaomi")
    e.Dial()
    e.DialXiaomi()
}

三 多态

package main

import "fmt"

type PhoneIf interface {
    Dial()
    Feature()
}

type Apple struct {
    apple_feature string
}

func (apple *Apple) Dial() {
    fmt.Println("Dial from Iphone")
}

func (apple *Apple) Feature() {
    fmt.Println("Iphone feature")
}

type Huawei struct {
    huawei_feature string
}

func (huawei *Huawei) Dial() {
    fmt.Println("Dial from Huawei")
}

func (huawei *Huawei) Feature() {
    fmt.Println("Huawei feature")
}

func main() {
    var phone PhoneIf

    phone = &Apple{}
    phone.Dial()
    phone.Feature()

    phone = &Huawei{}
    phone.Dial()
    phone.Feature()

    phone2 := &Huawei{}
    phone2.Dial()
    phone2.Feature()
}

四 补充说明

  • go中的public就是名称首字母大小写,大写为public,假如一中的 p.color = "black" 用在不同的包将出错, 此时需要将coler改成Color
  • 二和三中的 func内 struct和 interface 用* 和不用* 都行, 一般要操作成员变量的时候,用* 更妥,更有效读取和变更成员变量的值

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值