I see this quite a lot and I was wondering if there was a way to refactor this nicely to avoid the massive switch? This is a method in a factory: RoomControllerFactory, instantiating a game location based on its type. Here's an example from a 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);
Luckily, JavaScript's object literals are a pretty good alternative for most switch statement use-cases I can think of. The idea is to define an object with a key for each case you would have in a switch statement. Then you can access its value directly using the expression you would pass to the switch statement.
There are 3 types of factory design pattern. Basically, Simple factory is not a design pattern. So, we will not talk about this rather we will cover its relevance while studying the factory method and in this post, I will only be explaining the factory method.
A potential disadvantage of Factory methods is that clients might have to sub-class the creator class just to create a particular concrete product object. Subclassing is fine when the client has to subclass the creator class anyway, but otherwise, the client now must deal with another point of evolution.
In other words, subclasses are responsible to create the instance of the class. The Factory Method Pattern is also known as Virtual Constructor.
Seeing as you are using a hack to provide the enum functionality - why don't you add a method to your enum:
public static const ROOMONE : LocationType = new LocationType("locationone",
function(...) : RoomController {
return new RoomOneController
}
);
(excuse any silly mistakes - actionscript isn't my first language!)
In java I would do similar with:
public enum LocationType {
ROOMONE {
@Override
public RoomController getRoomController() {
return new RoomOneController();
}
};
public abstract RoomController getRoomController();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With