如何为泛型类型创建工厂?

时间:2015-07-24 13:54:34

标签: java generics factory

我需要创建一个可以返回具有特定参数化类型的对象的Factory对象。也就是说,我需要在factory方法中指定对象的参数化类型。一个例子是我能想到解释它的最好方法,所以请考虑以下类定义。

 |  setheading(self, to_angle)
 |      Set the orientation of the turtle to to_angle.
 |      
 |      Aliases:  setheading | seth
 |      
 |      Argument:
 |      to_angle -- a number (integer or float)
 |      
 |      Set the orientation of the turtle to to_angle.
 |      Here are some common directions in degrees:
 |      
 |       standard - mode:          logo-mode:
 |      -------------------|--------------------
 |         0 - east                0 - north
 |        90 - north              90 - east
 |       180 - west              180 - south
 |       270 - south             270 - west
 |      
 |      Example (for a Turtle instance named turtle):
 |      >>> turtle.setheading(90)
 |      >>> turtle.heading()
 |      90

我基本上需要创建一个可以创建任何Dog(interface Color { int getColor(); } abstract class Animal<T extends Color> { T color; Animal(T col) { color = col; } public T getColor() { return color; } } class Dog<T extends Color> extends Animal<T> { public Dog(T col) { super(col); } public void woof() { System.out.println("Woof"); } } class Cat<T extends Color> extends Animal<T> { public Cat(T col) { super(col); } public void meow() { System.out.println("Meow"); } } class Blue implements Color { public int getColor() { return 1; } public void iAmBlue() { System.out.println("I am blue."); } } class Red implements Color { public int getColor() { return 2; } } // Expecting a base Factory interface that's something like this? public interface Factory<K extends Animal<? extends Color>> { public <T extends Color> K create(T color); } public class CatFactory implements Factory<Cat<? extends Color>> { @Override // I want this to return Cat<T>, not Cat<?> public <T extends Color> Cat<? extends Color> create(T color) { return new Cat<T>(color); } } Dog<Red>)的Factory对象,以及一个可以创建任何Cat(Dog<Blue>或{{1 }})。在构造对象时,我需要它能够返回Cat<Red>Cat<Blue>,而不是Dog<Red>Dog<Blue>。因此,这样的事情应该是有效的(不需要类型转换):

Animal<?>

1 个答案:

答案 0 :(得分:1)

dogFactory.create(new Blue()).getColor().iAmBlue(),我得出结论,你需要在工厂的某处保留Color类型。由于create()方法是目前唯一拥有它的方法,因此您需要在类级别提取它的类型参数。类似的东西:

public interface Factory<T extends Color, K extends Animal<T>> {
    public K create();
}

这需要将工厂实施更改为:

public class CatFactory<T extends Color> implements Factory<T, Cat<T>> {

    private T color;

    public CatFactory(T color) {
        this.color = color;
    }

    @Override
    public Cat<T> create() {
        return new Cat<T>(color);
    }

    public T getColor() {
        return color;
    }

}

现在,您可以通过实例化工厂来完成示例中所需的操作:

public static void main(String[] args) {
    CatFactory<Blue> blueCatsFactory = new CatFactory<Blue>(new Blue());
    blueCatsFactory.create().meow();
    blueCatsFactory.create().getColor().iAmBlue();
}
相关问题