lundi 14 septembre 2015

Avoid casting and instanceOf

I got an interface

public interface Details {
   // nothing needed until now
}

and two implementations

public class DetailsA implements Details {

    private BigDecimal betragA;

    public DetailsA() {
    }

    public BigDecimal getBetragA() {
      return this.betragA;
    }

    public void setBetragA(BigDecimal betragA) {
      this.betragA = betragA;
   }

}

public class DeailsB implements Details {

    private BigDecimal betragB;
    private boolean booleanB;

    public BetragB() {
    }

    public BigDecimal getBetragB() {
        return this.betragB;
    }

    public void setBetragB(BigDecimal betragB) {
        this.betragB = betragB;
    }

    public boolean isBooleanB() {
        return this.booleanB;
    }

    public void setBooleanB(boolean booleanB) {
        this.booleanB = booleanB;
    }

    // some more fields

}

I got a model class in which I want to use those details, depending on the instance.

 public class Model extends AbstractModel {

    private Details details;

    public void init(StoerungValue stoerung) {
        setDetails(stoerung.getSchaden().getDetails());
    }

    private void setDetails(Details details) {
        this.details = details;
    }

Then I have some operations like the following

    public boolean isBooleanB() {
        if (details instanceof DetailsB) {
            return ((DetailsB) details).isBooleanB();
        }
        return false;
    }

    public void setBooleanB(boolean booleanB) {
        if (details instanceof DetailB) {
            ((DetailB) details).setBooleanB(booleanB);
        }
    }

How can I avoid this casting and instanceOf stuff? Is any of the design patterns applicable here?

Aucun commentaire:

Enregistrer un commentaire