What is the difference between using a global variable and a Singleton? Java

0

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!

    
asked by Raikish 28.02.2018 в 18:34
source

2 answers

0

Your global variable can be reached anywhere in your code as your example in java, it should be declared public , the singleton design pattern serves to generate only one instance of an object as opposed to the class or global variable, this can be inside a package and not be publicly visible, imagine that you have a class that generates a connection to a database, and there are many processes that require that class, would generate multiple instances of connection to the database, with your singleton pattern you avoid opening as many instances of the database or any other object that you require to be unique.

    
answered by 28.02.2018 в 18:42
0

In java there are no global variables, what do exist are static variables.

A singleton is a design pattern that serves to limit the number of instances of a class to 1. Static variables are used to implement it, but this is not enough, since other instances must also be avoided.

    
answered by 28.02.2018 в 18:51