lundi 16 mars 2015

Avoiding code repetition when multiple concrete classes extend multiple abstract classes in Java


Vote count:

1




I have a scenario where multiple concrete classes extend multiple abstract classes. I am at a loss to come up with a clean structure, reduce the number of files and avoid code repetition.


The ask is to display various sensor values in different ways based on some criteria. Sensor values like temperature, voltage, current etc can have an anlaog widget, a numeric label or a combination of both. I have 3 abstract classes for the 3 different kind of views. These 3 abstract classes implement a method that defines how the view is to be drawn. Each sensor view extends the 3 abstract classes and implements methods to read the sensor, perform some engineering conversion and display the sensor value. The problem here is that the code implemented by the concrete classes is the same no matter what abstract class it extends. CAnalogTempView, CDigitalTempView and CCustomTempView all have the same implementation but extend different classes.


This seems awkward. The code is repeated and the number of source files increases by a factor of 3. Am I missing something simple here? Is there a pattern for a problem like this? Can I extend the sensor view classes at run time? The actual code is more complicated. I have over simplified the problem statement for clarity.



public abstract class CView
{
public abstract void draw();
public abstract void calculate();
}

public abstract class CAnalogView extends CView
{
public void draw()
{
// draw specific to analog view
}
}

public abstract class CDigitalView extends CView
{
public void draw()
{
// draw specific to digital view
}
}

public abstract class CCustomView extends CView
{
public void draw()
{
// draw specific to custom view
}
}

// concrete implementations
public class CAnalogTempView extends CAnalogView
{
public void calculate()
{
// read and calculate sensor value here
}
}

public class CDigitalTempView extends CDigitalView
{
public void calculate()
{
// calculate here. same as CAnalogTempView::calculate()
}
}

public class CCustomTempView extends CCustomView
{
public void calculate()
{
// calculate here. same as CAnalogTempView::calculate()
}
}


asked 1 min ago







Avoiding code repetition when multiple concrete classes extend multiple abstract classes in Java

Aucun commentaire:

Enregistrer un commentaire