lundi 9 novembre 2020

null pointer when using factory pattern in a java project

I am reading in player strategies from a .properties file which reads a string and decides what strategy to make. Works great except when I need to randomly produce a strategy, then when I try to call the function from within the class I get a null pointer. Would appreciate any advice. Here is the .properties file

#selects ~~~~~~

playerSelect1=smartSelection

playerSelect2=random

playerSelect3=random 

factory class

String[] selectTypes = {"randomCard", "highestRank", "smartSelection"};
public ISelectBehaviour createSelectStrategy(String selectType) {
 if (selectType == null || selectType.isEmpty())
            return new RandomCard();//null equiv
        if ("random".equals(selectType)) {
            Random r = new Random();
            int randomNumber = r.nextInt(selectTypes.length);
            String selectType2 = selectTypes[randomNumber];
            System.out.println("selected strat is: "+selectType2);
            createSelectStrategy(selectType2);
        }
        else if ("smartSelection".equals(selectType)) {
            return new SmartSelection();
        }
}

this strategy is called here in a player factory which is using the select strategy factory

selectType = gameProps.getProperty("playerSelect" + playerNumber);
 ISelectBehaviour select = selectFactory.createSelectStrategy(selectType);

and the null pointer occurs here, when the strategy pattern is meant to have attributed to a random select style

public NPC(int playerNumber, IFilterBehaviour filterBehaviour, ISelectBehaviour selectBehaviour){
        super(playerNumber);

        this.selectBehaviour = selectBehaviour;
    }
 public Card select(ArrayList<Card> hand, Hand trick, Whist.Suit trumps) {
        return selectBehaviour.select(hand, trick, trumps);
    }

}

Aucun commentaire:

Enregistrer un commentaire