jeudi 29 octobre 2020

Best way to use a Singleton object in main method as well as other surrounded methods in Java [duplicate]

Say I have a simple Singleton class below that has one attribute, a String variable. What's the best way to set up this Singleton class in my MainClass if I want to use it all throughout the code, not just the main function, but in all other functions (and other classes) as well?

public class Singleton
    {
        private static Singleton instance = null;
        public String text = null;
    
        private Singleton(){}
    
        public static Singleton getInstance(){
            if(instance == null){
                instance = new Singleton();
            }
            return instance;
        }
    
        public void setText(String text){
            this.text = text;
        }
    }


    public class MainClass
    {
        public static void main(String[] args){
            Singleton single = Singleton.getInstance();
            single.setText("asdf");
        }
        
        public void doStuff(){
            //....
            //....
            Singleton single2 = Singleton.getInstance();
            single2.setText("hello");
        }
    }

Would I do something like the following above where every new area I want to call the Singleton, I'd use getInstance and basically create a new variable (that seems repetitive), or should I create it at the top as a class variable of MainClass? That would mean it would throw errors since main is static and opens up a whole other can of worms as well I believe. I'm new to design patterns so any tips would be great!

Aucun commentaire:

Enregistrer un commentaire