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.