| 1 |
package main |
| 2 |
|
| 3 |
type Option interface { |
| 4 |
apply(*T) |
| 5 |
} |
| 6 |
|
| 7 |
type T struct { |
| 8 |
s string |
| 9 |
} |
| 10 |
|
| 11 |
type opt struct { |
| 12 |
name string |
| 13 |
} |
| 14 |
|
| 15 |
func (o *opt) apply(t *T) { |
| 16 |
println(o.name) |
| 17 |
} |
| 18 |
|
| 19 |
func BuildOptions() []Option { |
| 20 |
return []Option{ |
| 21 |
&opt{"opt1"}, |
| 22 |
&opt{"opt2"}, |
| 23 |
} |
| 24 |
} |
| 25 |
|
| 26 |
func NewT(name string, options ...Option) *T { |
| 27 |
t := &T{name} |
| 28 |
for _, opt := range options { |
| 29 |
opt.apply(t) |
| 30 |
} |
| 31 |
return t |
| 32 |
} |
| 33 |
|
| 34 |
func main() { |
| 35 |
t := NewT("hello", BuildOptions()...) |
| 36 |
println(t.s) |
| 37 |
} |
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|