Is there an alternative to switching in a factory method?

I see this quite a lot, and I was wondering if there is a way to reorganize this to avoid a massive switch? This is a method in the factory: RoomControllerFactory that instantiates a game location based on its type. Here is an example from the switch in the factory method:

switch (location.getType()) { case Location.ROOMONE: return new RoomOneController(location, data, view); case Location.ROOMTWO: return new RoomTwoController(location, data, view); case Location.ROOMTHREE: return new RoomThreeController(location, data, view); 
+6
source share
2 answers

The short answer is, switching factories, what they do - the whole point of this factory style is to centralize the build logic in one place, and not that it is littered around the code base.

As long as you don't use Static factory and coding in the IRoomControllerFactory interface, you get all the usual OOP benefits of replacing it at run time / for testing - after all you say "Yo RoomControllerFactory", give me room for this magic identifier! "

As another answer to your question, you may ask yourself why you need so many specific instances of RoomController? Perhaps in favor of composition over inheritance, could you reorganize things instead of Builder instead?

+3
source

Seeing how you use the hack to provide an enumeration function - why don't you add a method for your enumeration:

 public static const ROOMONE : LocationType = new LocationType("locationone", function(...) : RoomController { return new RoomOneController } ); 

(sorry any stupid mistakes - ActionScript is not my first language!)

In java, I would do something like:

 public enum LocationType { ROOMONE { @Override public RoomController getRoomController() { return new RoomOneController(); } }; public abstract RoomController getRoomController(); } 
+4
source

Source: https://habr.com/ru/post/894615/


All Articles