Golang 封装

Jackey Golang 2,760 次浏览 , 没有评论

person.go

package model

import "fmt"

type person struct {
  Name   string
  age    int // 其他包不能访问
  salary int
}

// 写一个工厂模式的函数,相当于构造函数
func NewPerson(name string) *person {
  return &person{
    Name: name,
  }
}

// 为了访问age 和 salary 我们编写一对 SetXxx 和 GetXxx 的方法
func (p *person) SetAge(age int)  {
  if age >0 && age < 150 {
    p.age = age
  } else {
    fmt.Println("年龄范围不正确")
  }
}

func (p *person) GetAge() int {
  return p.age
}

func (p *person) SetSalary(salary int)  {
  if salary > 3000 && salary < 30000 {
    p.salary = salary
  } else {
    fmt.Println("薪水范围不正确")
  }
}

func (p *person) GetSalary() int {
  return p.salary
}

main.go

package main

import (
  "fmt"
  "tianqi-api/tests/study/encapsue/model"
)

func main()  {
  p := model.NewPerson("gopher.cc")
  p.SetAge(10)
  p.SetSalary(5000)
  fmt.Println(p)
  fmt.Println("name =", p.Name, " age =", p.GetAge(), " salary =", p.GetSalary())
}

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Go