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, vie开发者_StackOverfloww);
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();
}
Short answer, factories switch, that's what they do - the whole point of this style of factory is to centralise the construction logic into a single place rather than having it littered around the codebase.
As long as you are not using a Static Factory and coding to an IRoomControllerFactory interface then you get all the usual OOP benefits of swapping him out at runtime / for testing - after all you're saying 'Yo RoomControllerFactory, give me a room for this magic identifier!'
As a further answer to your question, you may want to ask yourself why you need so many concrete instances of RoomController? Perhaps by favouring composition over inheritance you could refactor things to use a Builder instead?
精彩评论