go functional options pattern๐
go ๊ฐ๋ฐ ๋ฐฉ๋ฒ ์ค functional options pattern ์ ๊ฐ๋จํ ์ค์ต ์์ ์ฝ๋๋ฅผ ํตํด ์๊ฐ๋๋ฆฝ๋๋ค.
functional option ์ ํจ์/๋ฉ์๋๋ฅผ ์ํํ ๋ ๊ฐ๋ณ์ ์ธ ์ต์ ์ ์ค ์ ์๋ ๋ฐฉ๋ฒ์ ๋๋ค.
ํจ์/๋ฉ์๋๋ฅผ ์์ฑํ๊ณ ์ํ ๋, ์๋์ ๊ฐ์ ์ํฉ์ผ๋ ์ ์ฉํฉ๋๋ค.
- default parameter ๋ฅผ ์ค์ ํ๊ณ ์ถ๋ค.
- optionalํ ํ๋ผ๋ฏธํฐ ๋ฆฌ์คํธ๋ฅผ ๊ฐ๋ณ์ ์ผ๋ก ์ค์ ํ๊ณ ์ถ๋ค.
๊ตฌํ ๋ฐฉ๋ฒ
- optional ํ ํ๋ผ๋ฏธํฐ ๋ฆฌ์คํธ ์ญํ ์ ํด์ฃผ๋
option struct
๋ฅผ ์ ์ธ - ์์ struct ๋ฅผ ํฌ์ธํฐ ์ฐธ์กฐํ์ฌ ๊ฐ์ ์ค์ ํด์ฃผ๋
functional options
์์ฑ - ๊ตฌํํ๊ณ ์ ํ๋ ํจ์ ์๊ทธ๋์ณ์ ๊ฐ๋ณ์ธ์
functional options
ํ๋ผ๋ฏธํฐ๋ฅผ ์ค์ ํ์ฌ ๊ตฌํ
๊ฐ๋จํ ์์ ์ฝ๋
์๋ฅผ๋ค์ด ์ธ์ถ์ ํ๊ณ ์ถ์ ์ ๋ GoOut() ์ด๋ผ๋ function ์ ์ํํ๊ณ ์ถ์ต๋๋ค. GoOut() ์ ํ ๋๋ muffler, coat ๋ฅผ ์ ๊ณ ๋๊ฐ๋ฉด ์ข์๊ฑฐ๊ฐ์ต๋๋ค. ๊ทธ๋์ ์ด muffler, coat ๋ฅผ ์ ๊ณ ๋๊ฐ์ง ๊ฒฐ์ ํ๋ bool ํ๋๊ทธ๋ค์ optional ํ ํ๋ผ๋ฏธํฐ๋ก ๊ฐ์ง๋ค๊ณ ๊ฐ์ ํด๋ณด๊ฒ ์ต๋๋ค.
1. option struct ์ค์
๊ทธ๋์ muffler, ์ coat ๋ผ๋ bool field ๋ฅผ ๊ฐ์ง๋ GoOutOption
๋ผ๋ struct๋ฅผ ์ ์ธํด์ค๋๋ค. ํด๋น struct ๋ ์ด์ ๊ตฌํํ๊ณ ์ํ๋ GoOut() function ์ optional ํ parameter ๋ฆฌ์คํธ๋ก์จ์ ์ญํ ์ ํ๋ option struct
๊ฐ ๋ฉ๋๋ค.
type GoOutOption struct{
muffler bool
coat bool
... // ๋ ์ถ๊ฐ ํ๊ณ ์ถ์ parameter ๋ค์ field ๋ก ๋ ์ ์์ต๋๋ค.
}
2. functional options ์์ฑ
GoOutOption ์ muffler ์ ์ ๊ทผํ์ฌ ๊ฐ์ ์ค์ ํด์ฃผ๋ function ์ ๋ฆฌํดํด์ค๋๋ค. ์ฌ๊ธฐ์ ๋ฆฌํด ๋๋ func(option *GoOutOption)
์ด functional option
์ด ๋ฉ๋๋ค.
coat ์ ๊ฒฝ์ฐ๋ ๋ง์ฐฌ๊ฐ์ง๋ก ์ค์ ์ด ๊ฐ๋ฅํ๋๋ก ์์ฑํด์ค๋๋ค.
func WithMuffler(isEnabled bool){
return func(option *GoOutOption){
option.muffler = isEnabled
}
}
func WithCoat(isEnabled bool){
return func(option *GoOutOption){
option.muffler = isEnabled
}
}
3. ๊ฐ๋ณ์ธ์ functional options ํ๋ผ๋ฏธํฐ๋ฅผ ์ค์ ํ์ฌ ๊ตฌํ
์ ๋ coat ๋ ๊ธฐ๋ณธ์ ์ผ๋ก ์ ๊ณ ๋๊ฐ๊ณ muffler ๋ ๊ธฐ๋ณธ์ ์ผ๋ก ์ ๊ณ ๋๊ฐ์ง ์๋ ์ค์ ์ default ๋ก ์ฃผ๋ optional ํ๊ฒ ์ค์ ํ๊ณ ์ถ์ต๋๋ค.
๊ทธ๋์ ๋ด๋ถ์ ์ผ๋ก GoOutOption ๋ฅผ ๊ฐ์ง๊ณ , coat ๋ default ๊ฐ์ด true ์ด๊ณ muffler ๋ false ๊ฐ ๋๋๋ก GoOut() ์ ๊ตฌํํฉ๋๋ค.
์ฌ๊ธฐ์ functional option ์ธ func(option *GoOutOption)
๋ฅผ ๊ฐ๋ณ์ธ์๋ก ์ค์ ํด์ฃผ๋ฉด ํ๋ผ๋ฏธํฐ ๋ฆฌ์คํธ๋ฅผ ๊ฐ๋ณ์ ์ผ๋ก ๊ฐ์ง๋ ํจ์๋ก ๋ง๋ค ์ ์๊ฒ๋ฉ๋๋ค.
func GoOut(optFuncs ...func(option *GoOutOption)){
//1.์์ ์ ์ธํ option struct ๊ฐ์ default ๊ฐ์ผ๋ก ์ค์
option := GoOutOption{
coat : true
muffler: false
}
//option struct ๊ฐ์ ์ค์ ํด์ฃผ๋ ๊ฐ๋ณ์ธ์ functional options ์ํ
for i:= range optFuncs{
optFuncs[i](&option)
}
//GoOut~
}
์ด์ GoOut() ์ ์ํํ ๋ functional options ์ ๊ฐ๋ณ์ ์ผ๋ก ๋๊ธธ ์ ์์ต๋๋ค.
// ๋ฐ์ผ๋ก ๋๊ฐ ๋ coat ์ Muffler ๋ฅผ ๋๋ฅด๊ณ ๋๊ฐ๋ค.
GoOut(WithMuffler(true))
// ๋ฐ์ผ๋ก ๋๊ฐ๋ coat ๋ฅผ ์
์ง ์๊ณ ๋๊ฐ๋ค.
GoOut(WithCoat(false))
// ๋ฐ์ผ๋ก ๋๊ฐ ๋ coat ๋ง ์
๊ณ ๋๊ฐ๋ค.
GoOut()
๋ค๋ฅธ ์ต์ ์ ์ถ๊ฐํ๋ ๋ถ๋ถ๋ ์์ ์ธ๊ธ๋๋ฆฐ 1~3 ์ ๊ณผ์ ์ ๊ฑฐ์น๋ฉด ์ฝ๊ฒ ์ถ๊ฐํ ์ ์์ต๋๋ค.
golang option pattern ๊ด๋ จ ๊ธ