七叶笔记 » golang编程 » 《Golang学习数据结构和算法》中文版 第7篇

《Golang学习数据结构和算法》中文版 第7篇

《Learn Data struct ures and Algorithms with Go lang》作者: Bhagvan Kommadi

私有类数据( private class data)

私有类数据模式使类内部的数据安全。此模式是封装类数据的初始化。私有类中的属性写权限是受到保护的,属性在构造期间被设置。私有类模式通过在保留状态的类中保护信息来打印公开信息。类数据初始化的封装是这种模式的适用场景。

Account是一个带有账户明细和顾客名称的类。AccountDetails是Account的私有属性,而CustomerName是公有属性。Account的 JSON 化后有CustomerName作为公共属性。在Go里AccountDetails是包属性(作为私有类数据):

 //main package has examples shown
// in Hands-On Data Structures and algorithms with Go book
package main
// importing fmt and encoding/json packages
 import  (
  " encoding / json "
  "fmt"
)
//AccountDetails struct
type AccountDetails struct {
  id string
  accountType string
}
//Account struct
type Account struct {
  details *AccountDetails
  CustomerName string
}
// Account class method setDetails
func (account *Account) setDetails(id string, accountType string) {
  account.details = &AccountDetails{id, accountType}
}  

如下列代码所示,这个Account类有getId方法,返回私有类属性id:

 //Account class method getId
func (account *Account) getId() string{
  return account.details.id
}
//Account class method getAccountType
func (account *Account) getAccountType() string{
  return account.details.accountType
}  

main方法调用Account的带CustomerName的初始化方法。账户明细由setDetails方法设置:

 // main method
func main() {
  var account *Account = &Account{CustomerName: "John Smith"}
  account.setDetails("4532","current")
  jsonAccount, _ := json.Marshal(account)
  fmt.Println("Private Class hidden",string(jsonAccount))
  fmt.Println("Account Id",account.getId())
  fmt.Println("Account Type",account.getAccountType())
}  

运行以下命令:

 go run privateclass.go  

下一节让我们看看代理模式。

下一篇:

上一篇:

相关文章