zoukankan      html  css  js  c++  java
  • golang 接口interface 多态

    多态就是多重形态。

    案例: 

    收入的案例:

    package main
    
    import (
    	"fmt"
    )
    
    type Income interface {
    	calculate () float64
    	source() string
    
    }
    //固定账单项目
    type FixedBuilding struct {
    	ProjectName string
    	biddedAcount float64
    
    }
    // 定时和材料项目
    type TimeAndMetiarl struct {
    	ProjectName string
    	WorkHours int64 
    	WorkRate float64
    
    }
    
    func (f FixedBuilding)calculate() float64 {
    
    	return f.biddedAcount
    	
    }
    
    func (f FixedBuilding)source() string {
    	return f.ProjectName
    
    }
    
    //通过广告点击获得收入
    type Advertise struct {
    	dName string
    	Clickout int
    	incomePerclick float64
    }
    
    func (a Advertise)calculate() float64 {
    	// a.incomePerclick*a.Clickout
    	return a.incomePerclick*float64(a.Clickout)
    	
    }
    
    func (a Advertise)source() string {
    	return a.dName
    
    }
    
    func calculateNetIncome(ic []Income)float64  {
    	netIncome :=0.0
    	for _,v := range ic{
    		fmt.Printf("收入来源:%s 收入金额:%+v 
    ",v.source(),v.calculate())
    		netIncome +=v.calculate()
    	}
    
    	return netIncome
    	
    }
    
    func main()  {
    	p1 :=FixedBuilding{
    		"项目1",
    		8000,
    	}
    
    	p2 :=FixedBuilding{
    		"项目2",
    		9000,
    	}
    
    	p3 :=Advertise{
    		dName:          "百度",
    		Clickout:       100,
    		incomePerclick: 60,
    	}
    
    	p4 :=Advertise{
    		dName:          "谷歌",
    		Clickout:       10,
    		incomePerclick: 80,
    	}
    
    	ic := []Income{p1,p2,p3,p4}
    
    	fmt.Println(calculateNetIncome(ic))
    
    
    	
    
    
    	
    }





    /* out

    收入来源:项目1 收入金额:8000
    收入来源:项目2 收入金额:9000
    收入来源:百度 收入金额:6000
    收入来源:谷歌 收入金额:800
    23800



    */

      

  • 相关阅读:
    mac下的一个类似“_kbhit()”实现
    mac使用备注
    open()打开文件失败对应的各种错误码
    xcode显示行号show gutter
    下载google code中源码的几个工具
    HTML5迷你游戏作验证码
    Linux+eclipse+gdb调试postgresql源码
    S-Nim
    【求助】从大表中删除小表中存在的记录问题
    Binary Tree Zigzag Level Order Traversal (LeetCode) 层序遍历二叉树
  • 原文地址:https://www.cnblogs.com/zexin88/p/14942253.html
Copyright © 2011-2022 走看看