Last active
June 18, 2018 14:01
-
-
Save sgnn7/a49e76c1a2f3e4805c95e72c60e020e1 to your computer and use it in GitHub Desktop.
Instantiate an abstract Golang struct dynamically with parameters
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 | |
// Author: Srdjan Grubor | |
// License: Apache-2.0 | |
import ( | |
"fmt" | |
) | |
// Interface common for all classes | |
type MainInterface interface { | |
GetId() string | |
} | |
// First type of object | |
type FirstType struct { | |
Id string | |
} | |
func (ft *FirstType) GetId() string { | |
return ft.Id | |
} | |
// FirstType factory | |
func InitializeFirstType(id string) MainInterface { | |
return &FirstType{Id: id} | |
} | |
// Second type of object | |
type SecondType struct { | |
Id string | |
} | |
func (st *SecondType) GetId() string { | |
return st.Id | |
} | |
// SecondType factory | |
func InitializeSecondType(id string) MainInterface { | |
return &SecondType{Id: id} | |
} | |
func main() { | |
// Map of strings to factories | |
classes := map[string]func(string) MainInterface{ | |
"first": InitializeFirstType, | |
"second": InitializeSecondType, | |
} | |
// Create a new FirstType object with value of 10 using the factory | |
newObject := classes["first"]("10") | |
// Show that we have the object correctly created | |
fmt.Printf("%v\n", newObject.GetId()) | |
// Create a new SecondType object with value of 20 using the factory | |
newObject2 := classes["second"]("20") | |
// Show that we have the object correctly created | |
fmt.Printf("%v\n", newObject2.GetId()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment