While reading up on the Class Adapter pattern in Head First Design Patterns, I came across this sentence:
class adapter... because you need multiple i
Class Adapters are kind of possible in Java by using single inheritance. As an example from Design pattern for dummies, suppose we have to adapt AWT checkboxes to be used alongside with Swing checkboxes, we can write a class adapter for this.
The UI code in Swing to determine if a check box is checked is done with the isSelected method. But, AWT check boxes dont support isSelected(), they use getState() instead.
So we can write an adapter to wrap an SWT check box and adapt the getState() to isSelected()
public class CheckboxAdapter extends Checkbox
{
public CheckboxAdapter(String n)
{
super(n);
}
public boolean isSelected()
{
return getState();
}
}
Now we can handle AWT adapted check boxes as we would standard Swing check boxes when it comes to the isSelected method.
public void itemStateChanged(ItemEvent e)
{
String outString = new String("Selected: ");
for(int loopIndex = 0; loopIndex
<= checks.length - 1; loopIndex++){
if(checks[loopIndex].isSelected()) {
outString += " checkbox " + loopIndex;
}
}
text.setText(outString);
}
EDIT: True class adapter are not possible in Java, if they were we could inherit from multiple classes, which we want to mimic in an adapter class.
Also see http://www.journaldev.com/1487/adapter-design-pattern-in-java-example-tutorial for two examples in Java using Class Adapter and Object adapter, to achieve same result.