封裝
- 基本介紹
- 封裝介紹
- 封裝的好處
- golang如何體現封裝
- 封裝的實作
基本介紹
Golang仍然有面向物件編程的繼承、封裝和多型的特性,只是實作的方法和其它OOP語言不一樣,下面我們來看看Golang是如何實作封裝的,
封裝介紹
封裝(encapsulation)就是把抽象出的欄位和對欄位的操作封裝在一起,資料被保護在內部,程式的其它包只有通過被授權的操作(方法)才能對欄位進行操作,
封裝的好處
- 隱藏實作細節,
- 可以對資料進行驗證等,
golang如何體現封裝
- 對結構體中的屬性進行封裝
- 通過方法,包實作封裝
封裝的實作
- 將結構體,欄位(屬性)的首字母小寫(其他包不能使用,類似private),
- 給結構體所在包提供一個工廠模式的函式,首字母大寫,類似一個建構式,
- 提供一個首字母大寫的set方法(類似其它語言的public),用于對屬性判斷并賦值,
- 提供首字母大寫的get方法,用于獲取屬性的值,
特別說明:在Golang開發中并沒有特別強調封裝,這點并不像Java,所以不能總是用java的語法特性來看待Golang,Golang本身對面向物件的特征做了簡化,
代碼實作:
student.go
package model
import(
"fmt"
)
type student struct{
name string
age int
}
func NewStudent(name string,age int) *student{
return &student{
name : name,
age : age,
}
}
func (this *student) GetName()string{
return this.name
}
func (this *student) SetName(name string){
this.name = name
}
func (this *student) GetAge()int{
return this.age
}
func (this *student) SetAge(age int){
//對年齡合法性校驗
if age > 0 && age <150{
this.age = age
}else{
fmt.Println("年齡不合法...")
}
}
test.go
package main
import(
"fmt"
"go_code/OOP/model"
)
func main() {
stu := model.NewStudent("Casey",18)
fmt.Println(*stu)
stu.SetName("321")
fmt.Println(stu.GetName())
stu.SetAge(20)
fmt.Println(stu.GetAge())
}
運行結果:

博主首頁鏈接:https://blog.csdn.net/weixin_44736475
原創不易,希望大家多多支持
如果文章對你有幫助,記得一鍵三連哦!??????
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/264434.html
標籤:AI
