mercredi 21 mars 2018

Looping over heterogeneous collection

The example is as follows: I have a Box that needs to be filled with some Things. I'm interested only in weight of each thing. Also, beside weight, I need to correctly identify the thing that I'm measuring. Each thing type has different Id type. In this case I have toys and fruits, which have ToyId and FruitId respectively. In the end, I need to be able to print thing identifier and thing weight.

Question: Is it somehow possible to access specific methods on ThingIds without using instanceof operator (as in example)?

class Color{}
interface ThingId {}

class FruitId implements ThingId {
    String name;    //"apple", "orange", ...
    FruitId(String name){  this.name = name; }
    String getName(){ return this.name; }
}

class ToyId implements ThingId {
    String shape;   //"square", "circle", ...
    Color color;    //"red", "blue"...
    ToyId(String shape, Color color){ this.shape = shape; this.color = color; }
    String getShape(){ return this.shape; }
    Color getColor(){ return this.color; }
}

class Thing{
    ThingId thingId;
    Integer weight;
    public Thing(ThingId thingId, Integer weight){
        this.thingId = thingId;
        this.weight = weight;
    }
    ThingId getThingId(){ return this.thingId; }
    Integer getWeight(){ return this.weight; }
}

class Box {
    Set<Thing> things = new HashSet<>();

    void addThing(Thing thing){
        this.things.add(thing);
    }

    Collection<Thing> getThings(){
        return this.things;
    }
}

class Program {
    public static void main(String[] args) {
        FruitId appleId = new FruitId("apple");
        Thing apple = new Thing(appleId, 1);
        ToyId cubeId = new ToyId("square", new Color());
        Thing cube = new Thing(cubeId, 22);

        Box box = new Box();
        box.addThing(apple);
        box.addThing(cube);

        for(Thing t : box.getThings()){
            System.out.print("Thing Id is: ");
            if(t.getThingId() instanceof FruitId) { //any other possibility than using instance of?
                process((FruitId)t.getThingId());
            }
            if(t.getThingId() instanceof ToyId){    //any other possibility than using instance of?
                process((ToyId)t.getThingId());
            }
            System.out.println("Weight is : " + t.getWeight());
        }
    }

    static void process(FruitId fruitId){
        System.out.println(fruitId.getName());
    }

    static void process(ToyId toyId){
        System.out.println(toyId.getShape() + toyId.getColor());
    }
}

Aucun commentaire:

Enregistrer un commentaire