One possibility is to use an enumeration. At the simplest level, you can replace constants of type Rose.NAME with enumeration values and preserve the internal mapping between enum values and classes to instantiate:
public enum Flowers { ROSE(Rose.class), OLEANDER(Oleander.class); private final Class<? extends Flower> flowerClass; Flowers(Class<? extends Flower> flowerClass) { this.flowerClass = flowerClass; } public Flower getFlower() { Flower flower = null; try { flower = flowerClass.newInstance(); } catch (InstantiationException e) {
Since flower class classes do not have a default constructor, Class.newInstance() cannot be used, so instantiating a class through reflection is a little more cumbersome (although possible). An alternative would be to use Prototype to create a new instance of colors.
This already ensures that you always keep the binding between possible color names and actual flower classes in sync. When you add a new color class, you must create a new enum value that includes matching to create new instances of the class. However, the problem with enum aproach is that the Garden instance that you are using is committed at startup. (If you do not pass it as the getFlower() parameter, but then there is a risk of losing consistency, i.e. it is more difficult to ensure that a certain group of colors is created in a certain garden).
If you want to be more flexible, you can use Spring to move the entire mapping between names and concrete (bean) classes to the configuration file. Then your factory just loads the ContextText Spring in the background and uses the display it displays. Whenever you introduce a new color subclass, you just need to add a new line to the configuration file. Again, this approach, in its simplest form, requires you to install the Garden bean instance during setup.
If you want to switch between different gardens while you work and ensure consistency between gardens and flower groups, the best choice would be a factory using an internal name map for flower classes. While the display itself may again be stored in the configuration, but you can create factory instances with various Garden instances at runtime.
source share