zoukankan      html  css  js  c++  java
  • Generality

    学习了 Effective Go 中 Generality 小节的内容 https://golang.org/doc/effective_go.html#generality

    由于这个小节的内容稍有点抽象,因此写了以下示例程序以便加深理解。

    /* Ver1 与 Ver2 是 Version 的两种不同的具体实现。
     * NewShow 接受一个 Version 作为参数,并返回一个 Show。
     * NewShow 不管 Version 的具体实现,只要是 Version 都可以接受,
     *         并且不管 Show 的具体实现,本例子虽然只给出了一种 Show 的实现 (ShowVer)
     *         但事实上换另一种实现也是可以的。
     */
    
    package main
    
    import "fmt"
    
    type Version interface {
    	Is() string
    }
    
    type Show interface {
    	VerNum()
    }
    
    type ShowVer struct{
    	V string
    }
    func (s ShowVer) VerNum() {
    	fmt.Println("Ver.", s.V)
    }
    
    type Ver1 struct {
    	V string
    }
    func (v Ver1) Is() string {
    	return fmt.Sprint(v.V)
    }
    
    type Ver2 struct{}
    func (v Ver2) Is() string {
    	return "2"
    }
    
    func main() {
    	ver1 := Ver1{"1"}
    	ver2 := Ver2{}
    	show1 := NewShow(ver1)
    	show2 := NewShow(ver2)
    	show1.VerNum()
    	show2.VerNum()
    }
    
    func NewShow(ver Version) Show {
    	v := ver.Is()
    	return ShowVer{v}
    }
    

      

    本程序的结果是,打印

    Ver. 1

    Ver. 2

  • 相关阅读:
    服务管理命令
    软件管理
    Qt软件打包与发布(windeployqt工具)
    03
    第一章 BP神经网络
    代理模式 与 Spring AOP
    java 回调机制
    HashTable 实现
    实现Singleton模式
    BST 汇总
  • 原文地址:https://www.cnblogs.com/ahui2017/p/6602697.html
Copyright © 2011-2022 走看看