mercredi 20 juin 2018

How to use a Abstract Factory Pattern with bounded typed parameter?

I am trying to use Abstract Factory Pattern with the bounded typed parameter with an example as follows:

CageAbstractFactory.java

public interface CageAbstractFactory {
    public Cage<?> createCage();
}

CageFactory.java

public class CageFactory {
    public static Cage<?> getCage(CageAbstractFactory factory) {
        return factory.createCage();
    }
}

XxxCageFactory.java (Xxx = Lion, Rat, etc)

public class XxxCageFactory implements CageAbstractFactory {
    @Override
    public Cage<Xxx> createCage() {
        return new XxxCage();
    }
}

Cage.java

public abstract class Cage<T extends Animal> { 
    protected Set<T> cage = new HashSet<T>();
    public abstract void add(T animal);
    public void showAnimals() {
        System.out.println(cage);
    }
}

XxxCage.java (Xxx = Lion, Rat, etc)

public class XxxCage extends Cage<Xxx> {
    @Override
    public void add(Xxx r) {
        cage.add(r);
    }
}

Animal.java

public class Animal {
    public String toString() {
        return getClass().getSimpleName();
    }   

}

class Rat extends Animal {}
class Lion extends Animal {}

AFP.java (Main class)

public class AFP {

    public static void main(String[] args) {
        Cage<?> rc = CageFactory.getCage(new RatCageFactory());
        Cage<?> lc = CageFactory.getCage(new LionCageFactory());
        rc.add(new Rat());
        rc.showAnimals();
        lc.add(new Lion());
    }

}

At lines rc.add(new Rat()) OR rc.add(new Lion()) the below error appears:

The method add(capture#3-of ?) in the type Cage<capture#3-of ?> is not applicable for the arguments (Rat)

It seems there is a type conversion error from Cage<?> to Cage<Rat>/Cage<Lion>

But the problem is the CageFactory.getCage(CageAbstractFactory factory) is returning Cage<?> which is only decided at runtime by the choice of the CageAbstractFactory class that is passed as argument (i.e. LionCageFactory OR RatCageFactory)

Aucun commentaire:

Enregistrer un commentaire