Singleton Design Pattern with JAVA service loaders

Neminda Prabhashwara :

I have been finding answers for my question on service loaders in the web and came across a solution that uses singleton design pattern.

I implemented my program according to that pattern and it gave me the expected output.

But I still have some points to clarify on singleton design pattern.

Why do we use private static variables and static methods on designing pattern?

This is the class I designed according to the pattern.

public class SingletonDesignPattern {

      private static SingletonDesignPattern singletonDesignPattern;
      private ServiceLoader<Cipher> serviceLoader;

      private SingletonDesignPattern() {

        serviceLoader = ServiceLoader.load(Cipher.class);

      }

      public static SingletonDesignPattern getInstance() {

        if (singletonDesignPattern == null)
          singletonDesignPattern = new SingletonDesignPattern();

        return singletonDesignPattern;

      }
}

I figured out that we use static methods because we don't create an instance of this class in any other class.

Any explanation that illustrates the purpose of using static private variables and static methods, other than the one I mentioned above are appreciated.

hturan :

The purpose of singleton pattern is to create only one instance of that class and use it everywhere. It is private because we don't want it to be created multiple times. It is static because we want to use the same created instance everywhere.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=360868&siteId=1