0

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.

1 Answers1

1

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.

hturan
  • 71
  • 1
  • 3
  • I get that the purpose of the method being `static` is because we create only one instance. But why the variables are `static`? if the static method can return this variable why should we define this variable `static`? – Neminda Prabhashwara Mar 28 '20 at 11:03
  • 1
    If you don't describe method static, you must call like this. ```SingletonDesignPattern sdp = new SingletonDesignPattern(); sdp.getInstance().somefunction(); ``` But this approach loads ServiceLoader in every use every – hturan Mar 28 '20 at 12:32