Very good, my dear colleagues, I wanted to ask you about the difference, advantages and disadvantages between using a global variable or the singleton pattern.
Then I leave a bit of code for you to see what I mean.
I understand that the global variable being static could be used anywhere in the program. Well the same thing would happen with the singleton, what advantages does it bring me to use a singleton, because it's so popular?
Singleton:
public class Singleton {
private Singleton() {}
private static Singleton instance = new Singleton();
private int num = 30;
public static Singleton getInstance() {
return instance;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
Global Variable:
public final class VariableGlobal {
private VariableGlobal(){}
public static int num = 30;
}
Main:
public class Main {
public static void main(String[] args) {
Singleton sing = Singleton.getInstance();
System.out.println(sing.getNum());
System.out.println(VariableGlobal.num);
}
}
Output:
Thank you very much everyone in advance!