Here is the situation I am looking to solve - A service is consuming JSON and doing some processing. Based on a string value in one of the JSON fields I want to instantiate one of a number of classes implementing an interface.
In essence I am trying to give the JSON input the ability to control which functionality to use.
A simplified version of my current solution is as follows
interface A{
val name: String
fun doSomething()
}
class choseImplementation(val jsonChoice: String){
inner class B: A{
override val name = "B"
override fun doSomething(){// Do B things}
}
inner class C: A{
override val name = "C"
override fun doSomething(){// Do C things}
}
init {
// Instantiate B and C
// Compare B.name and C.name with jsonChoice
// Choose the name that matches jsonChoice and expose the instantiated class
// The exposed class will be used in downstream processing
}
}
choseImplementation is given a string and exposes the proper implementation to be used by the system.
Right now I am manually instantiating each class within the init function and then comparing, which means I have to change the code in two places, add the D class then incorporate it in the init function
I want to be able to add a new inner class (D implements A) and have it automatically added to the process of being instantiated and selected.
Solutions outside this template are welcome
Thanks!
Aucun commentaire:
Enregistrer un commentaire