首页 > 其他 > 详细

go选项模式

时间:2019-12-19 21:34:01      阅读:70      评论:0      收藏:0      [点我收藏+]
package main

import "fmt"

type optionClient func(*options)

func setAge(a int) optionClient {
   return func(o *options) {
      o.Age = a
   }
}

func setSex(s int) optionClient {
   return func(o *options) {
      o.Sex = s
   }
}

type options struct {
   Age int
   Sex int
}

type Settings struct {
   Age  int
   Sex  int
   Name string
}

func NewSettings(Name string, clients ...optionClient) *Settings {
   option := options{26, 0}
   for _, f := range clients { //如果传入了自定义参数就会修改默认option,如果没有传入自定义参数,只是传入了姓名,就会用默认的option的值去设置
      f(&option)
   }
   return &Settings{
      Age:  option.Age,
      Sex:  option.Sex,
      Name: "",
   }
}

func main() {
   settings := NewSettings("Jerry", setAge(100), setSex(0))
   fmt.Print(settings.Age)
}




go选项模式

原文:https://www.cnblogs.com/hualou/p/12069689.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!