I have two activities that both of then extends from a base activity.
i.e.
CarActivity{
}
GasCarActivity extends CarActivity{
function onCreate(){
registerGasEvent() // so that onLowGasEvent() will work
}
function checkGas(){}
@Subscribe(threadMode = ThreadMode.MAIN)
function onLowGasEvent(){
}
}
ElectricCarActivity extends CarActivity{
function checkBattery(){}
@Subscribe(threadMode = ThreadMode.MAIN)
function onLowBatteryEvent(){
}
}
Now I need a HybridCarActivity that uses both GasCarActivity and ElectricCarActivity functions and life cycle events.
I'm also using eventbus library, how can I have the Subscribe function of both onLowGasEvent and onLowBatteryEvent in the HybridCarActivity?
What I can do here?
Java does not support multiple inheritance of implementation, but it supports multiple inheritance of interface. So, you can implement as many interfaces as you want. To avoid duplicates and share code between several classes, you can use delegates.
For example:
interface IGas {
checkGas();
onLowGasEvent();
}
interface IBattery
checkBattery();
onLowBatteryEvent();
}
class GasImpl implements IGas {
checkGas() {
...
}
onLowGasEvent() {
...
}
}
class BatteryImpl implements IBattery {
checkBattery() {
...
}
onLowBatteryEvent() {
...
}
}
class GasCar extends Car implements IGas {
IGas mGasImpl = new GasImpl(); // create it in your own code, or inject to inverse dependencies, etc.
checkGas() {
mGasImpl.checkGas();
}
onLowGasEvent() {
mGasImpl.onLowGasEvent();
}
}
class BatteryCar extends Car implements IBattery {
IBattery mBatteryImpl;
checkBattery() {
mBatteryImpl.checkGas();
}
onLowBatteryEvent() {
mBatteryImpl.onLowBatteryEvent();
}
}
HybridCar
will be something like this:class HybridCar extends Car implements IGas {
IGas mGasImpl;
IBattery mBatteryImpl;
checkGas() {
mGasImpl.checkGas();
}
checkBattery() {
mBatteryImpl.checkBattery();
}
}
EventBus
, you should keep subscribers as an Activity interface - but delegate it's implementation to the handlers as well. So, in the HybridActivity
: @Subscribe(threadMode = ThreadMode.MAIN)
function onLowGasEvent(){
mGasImpl.onLowGasEvent();
}
@Subscribe(threadMode = ThreadMode.MAIN)
function onLowBatteryEvent(){
mBatteryImpl.onLowBatteryEvent();
}
If onLow...Event
requires Context
, update interface methods to pass it as a parameter.
Hope it helps.