抽象介绍:
在定义一个结构体的时候, 实际上就是把一类事物的共有属性 (字段) 和行为(方法) 提取出来, 形成一个物理模型(模板), 这种研究问题的方法称为抽象.
封装:
把抽象出的字段和对字段的操作封装在一起, 数据被保护在内部, 程序的其它包只有通过被授权的操作(方法), 才能对字段进行操作.
1)将结构体, 字段 (属性) 的首字母小写
2)给结构体所在包提供一个工厂模式的函数, 首字母大写, 类似一个构造函数
3)提供一个首字母大写的 Set 方法(类似其它语言的 public), 用于对属性判断并赋值
- model.go
- package model
- import (
- "fmt"
- )
- type account struct {
- username string
- password string
- balance float64
- }
- func NewAccount() *account {
- return &account{}
- }
- // 设置账号
- func (user *account) SetUsername(username string) {
- if len(username) <6 && len(username)> 10 {
- fmt.Println("账号长度必须是 6 到 10 位")
- return
- }
- user.username = username
- }
- func (user *account) GetUsername() string {
- return user.username
- }
- // 设置密码
- func (user *account) SetPassword(password string) {
- if len(password) != 6 {
- fmt.Println("密码必须是 6 位")
- return
- }
- user.password = password
- }
- func (user *account) GetPassword() string {
- return user.password
- }
- // 设置余额
- func (user *account) SetBalance(balance float64) {
- if balance < 20 {
- fmt.Println("余额必须大于 20")
- return
- }
- user.balance = balance
- }
- func (user *account) GetBalance() float64 {
- return user.balance
- }
- main.go
- package main
- import (
- "fmt"
- "model"
- )
- func main() {
- user := model.NewAccount()
- user.SetUsername("admin123")
- user.SetPassword("123456")
- user.SetBalance(20)
- fmt.Println(user.GetUsername(), user.GetPassword(), user.GetBalance())
- }
继承:
来源: http://www.bubuko.com/infodetail-3348809.html