如何使用有界类型参数的抽象工厂模式?

时间:2018-06-20 11:46:18

标签: java generics design-patterns

我试图将Abstract Factory Pattern与有界的类型化参数一起使用,示例如下:

  

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等)

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等)

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(主类)

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());
    }

}

rc.add(new Rat())rc.add(new Lion())行,出现以下错误:

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

似乎从Cage<?>Cage<Rat> / Cage<Lion>的类型转换错误

但是问题是CageFactory.getCage(CageAbstractFactory factory)返回Cage<?>,这只能在运行时通过选择作为参数传递的CageAbstractFactory类(即LionCageFactoryRatCageFactory

2 个答案:

答案 0 :(得分:1)

您还需要概括CageAbstractFactory

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

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

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

答案 1 :(得分:1)

请勿像以下那样使用wildcard ?

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

但使用通用

public static <T extends Animal> Cage<T> getCage(CageAbstractFactory factory) {
    return factory.createCage();
}