Search code examples
javafactory-pattern

I'm learning about Java factory methods and want to know how to implement the example provided


Im reading Cracking The Coding Interview. In the section on Object Oriented Design they describe Factory Methods. They give an example but when I put this into eclipse it fails because GameType hasn't been defined. How would I implement this class?

Example Java Code

public class CardGame {
    public static CardGame createCardGame(GameType type) {
        if (type == GameType.Poker) {
            return new PokerGame();
        } else if (type == GameType.BlackJack) {
            return new BlackJackGame();
        }
    }
}

Solution

  • GameType looks like an enum or a class with something that simulate an enum, so I would do that. So it will be something like :

    public enum GameType {
        Poker, BlackJack;
    }
    

    Which give something like in your example :

    public class Main {
    
        public static void main(String[] args) {
            GameType type = GameType.Poker;
        }
    
    }