第14章 使用通道并发访问对象

2020-01-25  本文已影响0人  yezide
package main

import "fmt"
import "strconv"

type Persion struct {
    Name string
    salary float64
    chF chan func()
}

func NewPersion(name string, salary float64) *Persion {
    p := &Persion{name, salary, make(chan func())}
    go p.backend()
    return p
}

func (p *Persion) backend() {
    for f := range p.chF {
        f()
    }
}

func (p *Persion) SetSalary(salary float64) {
    p.chF <- func() {
        p.salary = salary
    }
}

func (p *Persion) Salary() float64 {
    fChan := make(chan float64)
    p.chF <- func() {
        fChan <- p.salary
    }
    return <- fChan
}

func (p *Persion) String() string {
    return "Person - name is: " + p.Name + " - salary is: " + strconv.FormatFloat(p.Salary(), 'f', 2, 64)
}

func main() {
    bs := NewPersion("Smith Bill", 2500.5)
    fmt.Println(bs)
    bs.SetSalary(4000.25)
    fmt.Println("Salary changed:")
    fmt.Println(bs)
}
上一篇下一篇

猜你喜欢

热点阅读