go 优雅的配置参数

package main

import "fmt"

type FinishedHouse struct {
	style                  int    //0: Chinese;  1:American; 2:European
	centralAirConditioning bool   // true 或 false  是否安装中央空调
	floorMaterial          string // 地面材料 ground-tile 或 wood
	wallMaterial           string // 墙面材料 paper 或 diatom-mud
}

type Option func(*FinishedHouse)

func NewFinishedHouse(options ...Option) *FinishedHouse {
	h := &FinishedHouse{
		style:                  0,
		centralAirConditioning: true,
		floorMaterial:          "wood",
		wallMaterial:           "paper",
	}
	for _, option := range options {
		option(h)
	}
	return h
}

func WithStyle(style int) Option {
	return func(h *FinishedHouse) {
		h.style = style
	}
}

func WithCentralAirConditioning(centralAirConditioning bool) Option {
	return func(h *FinishedHouse) {
		h.centralAirConditioning = centralAirConditioning
	}
}

func WithWallMaterial(wallMaterial string) Option {
	return func(h *FinishedHouse) {
		h.wallMaterial = wallMaterial
	}
}

func WithfloorMaterial(floorMaterial string) Option {
	return func(h *FinishedHouse) {
		h.floorMaterial = floorMaterial
	}
}
func main() {
	fmt.Printf("%+v\n", NewFinishedHouse()) // 使用默认选项

	fmt.Printf("%+v\n", NewFinishedHouse(WithStyle(1), WithWallMaterial("xiaoyu")))

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值