Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an alternative to switching in a factory method?

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);
like image 620
serenskye Avatar asked Aug 09 '11 08:08

serenskye


People also ask

What can I use instead of switch case?

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.

How many types of factory methods are there?

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.

What can be the disadvantages of 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.

What is the other name of Factory Method?

In other words, subclasses are responsible to create the instance of the class. The Factory Method Pattern is also known as Virtual Constructor.


1 Answers

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();
}
like image 63
Martyn Avatar answered Oct 11 '22 21:10

Martyn