1

If both don't have any difference then why singleton pattern comes into existence. If someone knows about good article or blog please share with me.

Singleton Object:

class Singleton{
   private static Singleton singleton = null;
   public static getInstance(){
      if(singleton == null) 
      singleton = new Singleton();
      return singleton;
   }

   public String getData() return "";

}

Static Function:

class Static{
    public static String getData() return "";
}
Vimit Dhawan
  • 597
  • 1
  • 7
  • 25
  • 1
    Singleton has the advantage when using more complex functions than just returning a String. Also google "java singleton use cases" and you get a ton of articles. It's also discussed here on stackoverflow: https://stackoverflow.com/q/228164/2135838 – Sascha Jun 09 '21 at 13:47
  • @Sascha Thanks for your response! I have googled but getting differences on singleton objects and static classes. My question here is in both the above approach which one is better to choose. If we have a state also in the singleton object. we can get with static variables then why we need a singleton object in the first place. – Vimit Dhawan Jun 09 '21 at 13:58
  • 1
    If you just want a bunch of static values you don't need a singleton object. A singleton is useful if you have more complex methods. They also can be declared by annotation and used by dependency injection in spring and EJB frameworks. So it depends heavily on your use case. – Sascha Jun 09 '21 at 14:04
  • 1
    avoid either one unless you have a **very** good reason to use it: https://williamdurand.fr/2013/07/30/from-stupid-to-solid-code/ – Timothy Truckle Jun 09 '21 at 14:05
  • I got this link https://softwareengineering.stackexchange.com/questions/34485/what-is-the-difference-between-all-static-methods-and-applying-a-singleton-patte – Vimit Dhawan Jun 09 '21 at 14:06
  • @TimothyTruckle Yeah I have agreed with you. I am looking for the difference so can I assume both are similar. sacha mentioned the dependency point that makes sense or I read that we can extend the interface. is there anything else? – Vimit Dhawan Jun 09 '21 at 14:10
  • 1
    The singleton pattern came into existence (as a pattern) two years before Java. – NomadMaker Jun 10 '21 at 00:13

1 Answers1

0

Depends on the scenario, in simple words

Static function can be used as helper function for some simple objective.

Singleton can be used to create more complex logics, if your logic depends on other classes then singleton is an option as it will allow you to inject your dependency.

Ankit Raonka
  • 6,429
  • 10
  • 35
  • 54