I have 4 classes that all implement a very similar block of code. The only difference is that each one needs to instantiate a separate Object
and Myclass()
at runtime. The below Action
classes are a simplified version (real code is much longer).
Normally I would pass in arguments to create the object and class based on what the caller provides. However, due to the callback extension (which is androids ActionCallback to be specific), I am unable to pass in any parameters to the Action
class.
What would be the best way of implementing a base class (like GenericAction()
below) which adapts for the different object/class each time. This would be a single source of truth and prevent the copy and paste of Action classes ABCD four times.
class ActionA : ActionCallback {
override suspend fun onAction(context: Context, glanceId: GlanceId, parameters: ActionParameters) {
doSomething(context, ObjectA, glanceId)
val constructSomething = MyClassA(context)
}
}
class ActionB : ActionCallback {
override suspend fun onAction(context: Context, glanceId: GlanceId, parameters: ActionParameters) {
doSomething(context, ObjectB, glanceId)
val constructSomething = MyClassB(context)
}
}
class ActionC : ActionCallback {
override suspend fun onAction(context: Context, glanceId: GlanceId, parameters: ActionParameters) {
doSomething(context, ObjectC, glanceId)
val constructSomething = MyClassC(context)
}
}
class ActionD : ActionCallback {
override suspend fun onAction(context: Context, glanceId: GlanceId, parameters: ActionParameters) {
doSomething(context, ObjectD, glanceId)
val constructSomething = MyClassD(context)
}
}
class GenericAction<T>(myObject: Any, myClazz: Class<T>) : ActionCallback {
override suspend fun onAction(context: Context, glanceId: GlanceId, parameters: ActionParameters) {
doSomething(context, myObject, glanceId)
val constructSomething = myClazz<T>(context)
}
}