1

I have the following class:

public class MotherFactory {

    private String food = "banana";

    private static FoodFactory<Banana> foodFactory = new BananaFactory();

    public MotherFactory() {        
    }
}

In this class i declare a FoodFactory for BananaHsm, which i hardcoded in (The food string has no use in this yet). What i want however, is that the declaration of the FoodFactory changes according to the food String. E.g.: For private String food = "apple", <BananaFactory> changes to <AppleFactory>, and new BananaFactory() to new AppleFactory and so on. i already thought of using a switch or if/else, however these would be declared inside the constructor, which doesnt make the variables usable for the whole instance. Are there any ways to do this?

NicO
  • 591
  • 2
  • 8
  • 21
  • 2
    You would make a FoodFactory with a static method ``getFactory(String food)`` that returns the appropiate factory. – f1sh Dec 03 '18 at 14:03
  • 1
    And use a `Map>` to avoid a long if/else or switch. – Andrew S Dec 03 '18 at 14:11
  • @f1sh wouldnt this only be possible when FoodFactory didnt need the type? e.g.: '' or 'Apple'? Also i cant edit the FoodFactory Class. – NicO Dec 03 '18 at 14:16
  • See [Abstract Factory Pattern](https://www.tutorialspoint.com/design_pattern/abstract_factory_pattern.htm) –  Dec 03 '18 at 14:20
  • You may actually prefer creating a `FruitFactory` which will accept a fruit string (or an enum if your purpose allows it) in the argument of a method `function Fruit createFruit(String fruit)` – Sirmyself Dec 03 '18 at 14:22
  • 2
    Create an interface Fruit; have all you fruits implement Fruit. (Sorry, comments don't format.) Create a FruitFactory with a method public T createFruit(Class fruitClass) { return fruitClass.newInstance() }. This should be a good starting point. – Steve11235 Dec 03 '18 at 14:27

0 Answers0