Golang 工厂模式

1.基本说明

  Golang的结构体没有构造函数,通常可以使用工厂模式类解决这个问题。

应用场景:

  一个结构体的声明是这样的:

  pcakage model

  type Student struct{

    Name string

  }

因为这里的Student的首字母S是大写的,如果我们想在其他包创建Student的实例,一如model包后,就可以直接创建Student的结构体的变量,但是如果首字母是小写的,比如是 :

type student struct{}就不行了,这时候需要“工厂模式”。

2.声明工厂模式

//定义一个结构体 student
type student struct{
    Name string
    Age int
}
//因为studen结构体首字母是小写,因此是只智能在莫得了使用
//我们通过工厂模式来解决
func NewStudent(n string,s int) *student{
    return &student{
        Name:n,
        Age:s,
    }
}

 

posted @ 2021-06-07 10:50  创客未来  阅读(88)  评论(0编辑  收藏  举报