Golang object-oriented programming-factory pattern creation example

Description

Golang's structure has no constructor, and the factory pattern can usually be used to solve this problem.

Introduce

Look at a demand:

package main
type Student struce{
    
    
  Name string
  ...
}

Because the first letter S of Student here is capitalized, if we want to create an instance of Student in other packages, we only need to import the package and create variables (instances) of the Student structure directly. But here comes the question, what should I do if the first letter is lowercase? ->Factory model to solve.

The factory pattern creates an instance across packages

student.go

package model

type student struct{
    
    
	Name string
	Age int
}

func NewStudent(name string,age int) *student{
    
    
	return &student{
    
    
		Name : name,
		Age : age,
	}
}

test.go

package main

import(
	"fmt"
	"go_code/OOP/model"
)

func main() {
    
    
	 
	stu := model.NewStudent("Casey",18)
	fmt.Println(*stu)
}

If the name of the student structure field is changed to name, can we access it normally?
Solution (similar to getter and setter in java)
student.go

package model

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
}

test.go

package main

import(
	"fmt"
	"go_code/OOP/model"
)

func main() {
    
    
	 
	stu := model.NewStudent("Casey",18)
	fmt.Println(stu.GetName())
}

Link to the blogger's homepage: https://blog.csdn.net/weixin_44736475
Originality is not easy, I hope you can support
it. If the article is helpful to you, remember to click three links! ❤️❤️❤️

Guess you like

Origin blog.csdn.net/weixin_44736475/article/details/114176256