Home > Blockchain >  can i add an extra public method in singleton class in java
can i add an extra public method in singleton class in java

Time:02-11

I have a singleton class and I added the msg method but I'm not sure if is okay to add it to the singleton class or not

public class Singleton {
    private static Singleton single_instance = null;
    private Singleton() {
       
    }

    public void msg(String msg){  
        System.out.println(msg);
    } 

    public static Singleton getInstance() {
        if (single_instance == null) {
            single_instance = new Singleton();
        }

        return single_instance;
    }
}

CodePudding user response:

Singleton is a Creational Design Pattern, which ensures that only one object of its kind exists and provides a single point of access to it for any other code. Aside from that, it is just an ordinary class that can have as many public methods as will need to satisfy the requirements for which it was designed.

Singleton objects can mutate (change the value of its internal attributes - variables), or can be immutable (for example, Java enums can be used to create Singleton instances).

Using your class as an example, you can do something like this and be perfectly legal:

public class Singleton {
    private static Singleton single_instance = null;
    private String message = "none";
    private Singleton() {
       
    }

    public void showCurrentMessage(){  
        System.out.println(msg);
    }
    public void updateMessage(String msg) {
        this.msg = msg;
    }

    public static Singleton getInstance() {
        if (single_instance == null) {
            single_instance = new Singleton();
        }

        return single_instance;
    }
}

Mind you that we are strictly speaking of the legality of this approach. Another discussion to be had is regarding the practicality of the approach where you need to consider many things like:

  1. Testability of the code - one of the reasons why Singleton are not liked very much
  2. Usability in multithreaded applications - Many safeguards are needed when objects mutate in multithreaded context.

There could be many others; albeit some of those (if not all) apply to non-Singleton objects as well.

  • Related