Java series: Singleton design pattern – Part 3

 In Self-Development, Tech Corner

The singleton design pattern is one of the most famous and controversial creational design patterns. A singleton class is a class which will be instantiated only once during the lifetime of the application. For example, there will be only one object shared for all the resources.

1. SINGLETON DESIGN PATTERN – APPLICATION

The singleton methods are thread safe. Multiple parts of the application can use the singleton methods at the same time. In some cases, they even access a shared resource within the Singleton class. The perfect example on when to use a singleton class is a logger implementation in which all the resource write in the same log file and is thread safe. Other examples:

  • database connections and shared network resources;
  • whenever the application needs to read a file from the server. Only in this case the object of the application will be able to access the files stored on the server.
  • config files;

2. JAVA APPLICATION

In java, a singleton is a class with a private constructor. The singleton class keeps a field with the instance of the class itself. The object is created using the get method, which calls the constructor if the instance hasn’t been initiated yet. Earlier, we mentioned that this pattern is the most controversial. WHY? Because of the many implementations for the instance generation. It must be thread safe, but it also must be efficient. In the examples we have two solutions.

import java.nio.file.Files;
import java.nio.file.Paths;

public class LoggerSingleton{

private static Logger logger;
    private String logFileLocation="log.txt";
    private PrintWriter pw;
    private FileWriter fw;
    private BufferedWriter bw;

    private Logger(){
       fw = new FileWriter(logFileLocation, true);
       bw = new BufferedWriter(fw)
       this.pw = new PrintWriter(bw);
    }

   public static synchronised Logger getLogger(){
       if(this.logger==null){
          logger=new Logger();
       }
       return this.logger;
    }

   public void write(String txt){
       pw.println(txt);
    }
}

The log file will be accessed frequently. For that reason, the print writer via a buffered writer makes sure that the file doesn’t open and close multiple times.

The second implementation includes a private class which holds a static field of the instance of the Singleton class. The private class is only accessed within the singleton class i.e. only from the get method.

public class Logger{

    private static class LoggerHolder(){
         public static Singleton instance=new Singleton();
    }

    private Logger(){
    // init
    }

    public static Logger getInstance(){
        return LoggerHolder.instance;
    }
}

The singleton class then can be used from any other class inside the app:

Logger log=Logger.getInstance();
log.write("something");

3. PROS AND CONS OF SINGLETON FACTORY DESIGN PATTERN

Pros:

  • the singleton class is instantiated only once in the life cycle of the app;
  • you can use it as many times needed;
  • the singleton class allows thread safe access to shared resources;
  • the singleton class cannot be extended and if it is implemented correctly i.e. the get method should be synchronized and static,
    it is thread safe;

Extra: I recommend you to create an interface first. Then design the singleton class itself. It is easier to test the interface;

 

Cons:

  • problems during testing. (when the singleton class accesses a shared resource and the execution of the tests is important);
  • the singleton class also hides some of the dependencies in the code. Eg. creates dependencies that are not explicitly created;
  • using singleton without a factory pattern breaks the single responsibility principle. This happens because the class is managing its own life cycle;

In the following blog post, we will tackle builder and observer design patterns. Subscribe below and never miss a story from our Java series: “Good practices and recommendations”.

Recommended Posts
java developerjava developer

SINGULAR STORY IN YOUR INBOX

Get news about career opportunities and product updates once a month.