zoukankan      html  css  js  c++  java
  • golang 面向对象

    一 对象封装

    package main
    
    import "fmt"
    
    type Phone0 struct {
    	number  string
    	color string
    }
    func (p Phone0) Dial() {
    	fmt.Printf("Dail from %s ; color is %s
    ", 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 
    ", 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 
    ", 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 用* 和不用* 都行, 一般要操作成员变量的时候,用* 更妥,更有效读取和变更成员变量的值
  • 相关阅读:
    Quartz2.0以上版本的单机和集群
    Mysql的Haproxy反向代理和负载均衡
    spring AOP原理解析
    Restful接口调用方法超详细总结
    mysql数据库主从同步
    数据备份的OSS接口
    读取properties配置文件的方法
    算法学习——堆排序(二叉树排序)
    回溯算法的实现
    冒泡排序
  • 原文地址:https://www.cnblogs.com/bushuwei/p/15495324.html
Copyright © 2011-2022 走看看