Last active
July 3, 2020 11:02
-
-
Save songtianyi/e50386230ed38257e3cb7dca8cc9f8bc to your computer and use it in GitHub Desktop.
add init options for legacy code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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