2016-11-28 58 views
1

我有以下的工廠轉換工廠模式吉斯模塊

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

我曾嘗試這樣做是爲了將其轉換成吉斯模塊行話:

@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.

我的最終目標是通過這個工廠即以具有不同的實現結合

FruitFactory,FruitFactory

到具體實現。

這可以更改爲使用提供者或其他任何東西,我不是這種方法太死板

有誰知道如何解決這一問題?

+0

你最終的目標是什麼?它是否將'FruitFactory 'FruitFactory '綁定到具體實現? –

+0

@DavidRawson,是的,這是最終的目標。是我可以把任何水果放在這個工廠裏並初始化它。 – Schumi

+0

太棒了!你能編輯你的問題來澄清這一點嗎?然後有人可以回答 –

回答

1

從你寫的東西到泛型都沒有任何變化。你希望你的泛型類型最終通過結核解決,對吧?我不知道,如果你的目標可以用類似下面的實現:

通用接口:

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

最後一個模塊,結合他們這樣:

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); 
     } 
    } 
} 
+0

目前我使用的是我上面提供的工廠,並且將它綁定爲這個綁定(新的TypeLiteral >(){})。((水果)FruitFactory.get Apple.class,new TypeOfFruits())); – Schumi

+0

我不知道我是否真的可以幫助更多 - 也許你可以澄清你的問題,所以它更清楚一點?同時,請查看Guice用戶指南(github.com/google/guice/wiki/Motivation)。你的Guice解決方案至少應該看起來像他們的一個例子。 –