Best way to implement the Factory Pattern in Java

后端 未结 8 1097
别那么骄傲
别那么骄傲 2020-12-09 13:59

I am trying to write a Factory Pattern to create either a MainMode or a TestMode in my program. The code I was previously using to create these objects was:

         


        
8条回答
  •  生来不讨喜
    2020-12-09 14:31

    The whole point of a Factory is that it should have the needed state to create your Game appropriately.

    So I would build a factory like this:

    public class GameFactory {
       private boolean testMode;
    
       public GameFactory(boolean testMode) {
         this.testMode = testMode;
       }
    
       public Game getGame(int numberRanges, int numberOfGuesses) {
         return (testMode) ? new MainMode(numberRanges, numberOfGuesses) : 
           new TestMode(numberRanges, numberOfGuesses, getRandom());
       }
    
       private int getRandom() {
         . . . // GUI code here
       }
    }
    

    Now you can initialize this factory somwhere in your app, and pass it in to whatever code needs to create a Game. This code now doesn't need to worry about what mode it is, and passing extra random params - it uses a well known interface to create Games. All the needed state is internalized by the GameFactory object.

提交回复
热议问题