Skip to content

Instantly share code, notes, and snippets.

@songtianyi
Last active July 3, 2020 11:02
Show Gist options
  • Save songtianyi/e50386230ed38257e3cb7dca8cc9f8bc to your computer and use it in GitHub Desktop.
Save songtianyi/e50386230ed38257e3cb7dca8cc9f8bc to your computer and use it in GitHub Desktop.
add init options for legacy code
package main
type AnyOther struct{}
type Module interface {
Classify(*AnyOther)
}
type SomeModule struct {
Param string
}
func CreateInternalSomeModule() Module {
return &SomeModule{Param: "some string"}
}
func (m *SomeModule) Classify(a *AnyOther) {
}
var modules = []Module{
CreateInternalSomeModule(),
}
func Create() {
// do something
}
func main() {
// original exported method
// we cannot customize the Param variable
Create()
}
package main
import "fmt"
// --- legacy code ---
type AnyOther struct{}
type Module interface {
Classify(*AnyOther)
}
type SomeModule struct {
Param string
}
func CreateInternalSomeModule() Module {
return &SomeModule{Param: "some string"}
}
func (m *SomeModule) Classify(a *AnyOther) {
}
var modules = []Module{
CreateInternalSomeModule(),
}
// --- legacy code ---
type Option interface {
Apply(Module)
}
type ModuleOption struct {
Param string
}
func (o *ModuleOption) Apply(m Module) {
if o.Param != "" {
m.(*SomeModule).Param = o.Param
}
fmt.Println(m.(*SomeModule))
}
func create(opts ...Option) {
for _, opt := range opts {
switch opt.(type) {
case *ModuleOption:
opt.Apply(modules[0])
}
}
}
func main() {
// original exported method
create()
// add options
// so the original method still work
create(&ModuleOption{Param: "other string"})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment