Singleton

Class that can only be instantiated only once.

public class Setting {

    private static Setting instance = null;

    private String name; 

    private String gender; 

    //Prevent creating new instance   
    private Setting() {}

    public static Setting getInstance() {
        //Only create when the instance is null else always return the same instance
        if (instance == null) {
            instance = new Setting();
        }
        return instance;
    }

    public setName(String name) {};

    public setGender(String gender){}; 

}

Start Game:

public class SuperMarioGame {

    public void startStageOne() {
        Setting setting = Setting.getInstance(); 
        setting.setName("Ian"); 
        setting.setGender("Male"); 

        GameStageOne game = new GameStageOne(setting); 
    }

}

Stage 2 in game:

public class SuperMarioGame {

    public void startStageTwo() {
        Setting setting = Setting.getInstance(); 
        GameStageTwo game = new GameStageTwo(setting); 

        //We didn't need to set the name and gender again, as we used the same instance
        println(setting.name) //Print "Ian"
        println(setting.getGender) //Print "Male"
    }

}

results matching ""

    No results matching ""