Best way to implement the Factory Pattern in Java

后端 未结 8 1001
别那么骄傲
别那么骄傲 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.

    0 讨论(0)
  • 2020-12-09 14:34
    interface ModeFactory {
        Mode createMode(int numberRanges, int numberOfGuesses);
    }
    
    class MainModeFactory implements ModeFactory {
        Mode createMode(int numberRanges, int numberOfGuesses) {
            return new MainMode(numberRanges, numberOfGuesses);
        }
    }
    
    class TestModeFactory implements ModeFactory {
        Mode createMode(int numberRanges, int numberOfGuesses) {
            return new TestMode(numberRanges, numberOfGuesses, randNo());
        }
    }
    
    ...
    
    play = modeFactory.createMode(numberRanges, numberOfGuesses);
    

    So at startup you create the appropriate mode factory, passing it in to wherever the play needs to be created.

    0 讨论(0)
提交回复
热议问题