我有以下工厂
public class AppleFactory<T extends Fruit>
extends AbstractAppleFactory<Class<T>, TypeOfFruits, Fruits<T>>
{
private static final AppleFactory factroy = new AppleFactory();
private AppleFactory()
{
}
public static Fruits<? extends Fruit> get(Class<? extends Fruit> clazz,
TypeOfFruits typeOfFruits)
{
return (Fruits<? extends Fruit>) factroy.getInstance(clazz, typeOfFruits);
}
@Override
protected Fruits<T> newInstance(Class<T> clazz, TypeOfFruits typeOfFruits)
{
final Fruits<T> fruits;
fruits = new FruitsImpl<T>(clazz, typeOfFruits,"hello");
return fruits;
}
}
我尝试通过这样做将其转换为 Guice 模块模式:
@ImplementedBy(AppleFactoryImpl.class)
public interface AppleFactory<T extends Fruit>
{
Fruits<? extends Fruit> get(Class<? extends Fruit> clazz,
TypeOfFruits typeOfFruits)
}
@Singleton
public class AppleFactoryImpl implements AppleFactory
{
@Override
public Fruits<? extends Fruit> get(Class<? extends Fruit> clazz,
TypeOfFruits typeOfFruits)
{
final Fruits<T> fruits;
fruits = new FruitsImpl<T>(clazz, typeOfFruits,"hello");
return fruits;
}
}
但是我在实现时遇到错误。它说它无法解析水果的 T 类型。
我的最终目标是通过这个工厂实现不同的实现,即绑定(bind)
FruitFactory, FruitFactory
具体实现。
这可以更改为使用提供程序或其他任何东西,我对方法不太严格
有人知道如何解决这个问题吗?
最佳答案
您所写的内容没有从通用到具体的变化。您希望您的泛型类型最终通过具体化来解决,对吧?我想知道您的目标是否可以通过以下方式实现:
通用接口(interface):
public interface FruitFactory<T extends Fruit> {
T get();
}
具体实现:
public class AppleFactory implements FruitFactory<Apple> {
@Override
public Apple get() {
return new Apple("apple");
}
}
public class OrangeFactory implements FruitFactory<Orange> {
@Override
public Orange get() {
return new Orange("orange");
}
}
最后是一个像这样绑定(bind)它们的模块:
public class FruitFactoryModule implements Module {
@Override
public void configure(Binder binder) {
binder.bind(new TypeLiteral<FruitFactory<Apple>>() {}).to(AppleFactory.class);
binder.bind(new TypeLiteral<FruitFactory<Orange>>() {}).to(OrangeFactory.class);
}
}
}
关于java - 将工厂模式转换为 Guice 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40840519/