網(wǎng)站首頁 編程語言 正文
僅做記錄 /* 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
相關(guān)推薦
- 2023-11-12 Docker中如何限制容器可用的 CPU
- 2023-03-25 詳解Python中命令行參數(shù)argparse的常用命令_python
- 2022-12-02 C語言實(shí)現(xiàn)動(dòng)態(tài)順序表的示例代碼_C 語言
- 2023-04-07 React替換傳統(tǒng)拷貝方法的Immutable使用_React
- 2022-11-03 C語言編寫掃雷小程序_C 語言
- 2022-12-06 nginx?pod?hook鉤子優(yōu)雅關(guān)閉示例詳解_nginx
- 2022-08-13 sparkstreaming寫入hive表報(bào)錯(cuò)問題解決
- 2022-07-12 mongoDB復(fù)雜查詢實(shí)例(嵌套多個(gè)數(shù)組和正則表達(dá)式使用)
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支