日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

Golang之函數(shù)選項(xiàng)模式

作者:傅里葉、 更新時(shí)間: 2022-07-03 編程語言
僅做記錄
/*
   Functional Options函數(shù)選項(xiàng)模式(簡稱FOP模式)
   既保持了兼容性,而且每增加1個(gè)新屬性只需要1個(gè)With函數(shù)即可,大大減少了修改代碼的風(fēng)險(xiǎn)
*/
package main

import "fmt"

/*
	Functional Options函數(shù)選項(xiàng)模式(簡稱FOP模式)
	既保持了兼容性,而且每增加1個(gè)新屬性只需要1個(gè)With函數(shù)即可,大大減少了修改代碼的風(fēng)險(xiǎn)
*/

type Student struct {
	Name string
	Age  int
	Sex  string
}

//定義類型函數(shù)
type StudentOption func(*Student)

//創(chuàng)建帶有age的構(gòu)造函數(shù)
func WithAge(age int) StudentOption {
	return func(s *Student) {
		s.Age = age
	}
}

func WithSex(sex string) StudentOption {
	return func(s *Student) {
		s.Sex = sex
	}
}

//創(chuàng)建帶有默認(rèn)值的構(gòu)造函數(shù)
func NewStudent(name string, options ...StudentOption) *Student {
	student := &Student{Name: name}
	for _, o := range options {
		o(student)
	}
	return student
}

func main() {
	student := NewStudent("fourier", WithAge(6), WithSex("男"))
	fmt.Println(student)
	teacher := NewTeacher("fourier", WithTeacherAge(20), WithGender("男"))
	fmt.Println(teacher)
}

type Teacher struct {
	Name   string
	Age    int
	Gender string
}

type TeacherOptions func(*Teacher)

func WithTeacherAge(age int) TeacherOptions {
	return func(teacher *Teacher) {
		teacher.Age = age
	}
}

func WithGender(gender string) TeacherOptions {
	return func(teacher *Teacher) {
		teacher.Gender = gender
	}
}

func NewTeacher(name string, options ...TeacherOptions) *Teacher {
	teacher := &Teacher{Name: name}
	for _, option := range options {
		option(teacher)
	}
	return teacher
}

原文鏈接:https://blog.csdn.net/qq_34562093/article/details/122319474

欄目分類
最近更新