zoukankan      html  css  js  c++  java
  • go语言 接口(多态)

    /* 多态行为的例子 */
    package main
    
    import "fmt"
    
    type notifer interface {
    	notify()
    }
    
    type user struct {
    	name  string
    	email string
    }
    
    type admin struct {
    	name string
    	age  int
    }
    
    type ad struct {
    	name string
    	age  int
    }
    
    //使用指针接收者实现了notofy接口,方法会共享接收者所指向的值user
    func (u *user) notify() {
    	fmt.Println("sendNotify to user", u.name)
    }
    
    //使用值接收者实现了notofy接口,方法使用a值的副本,对a的修改不会影响原值
    func (a admin) notify() {
    	fmt.Println("sendNotify to admin:", a.name)
    }
    
    //接收一个notifer接口类型的值,如果一个实体类型实现了该接口,
    //sendNotify函数会根据实体类型的值类执行notifer接口的notify行为,这个函数具有多态的能力。
    func sendNotify(n notifer) {
    	n.notify()
    }
    
    func main() {
    	user1 := user{"张三", "qq@qq.com"}
    	sendNotify(&user1) //张三
    
    	user2 := admin{"李四", 25}
    	sendNotify(user2) //李四
    
    	var n notifer
    	n = &user1
    	n.notify()
    }
    

      

  • 相关阅读:
    迭代器
    LinkedList存储一副扑克牌,实现洗牌功能。
    线程
    堆栈、队列
    路由-第7集
    javascript中split字符串分割函数
    this的用法
    什么是AOP面向切面编程
    Servlet与JSP的区别
    堆(heap)、栈(stack)、方法区(method)
  • 原文地址:https://www.cnblogs.com/shuai666/p/15260115.html
Copyright © 2011-2022 走看看