please tell me when to use getInstance() method in java.

Roster picture Roster · May 7, 2012 · Viewed 90k times · Source

When to use the getInstance() method in java and what is the meaning of getInstance(null)?

locationProvider = LocationProvider.getInstance(null); 

can anyone tell me the meaning of the above line?

Answer

Alexis King picture Alexis King · May 7, 2012

Classes that use getInstance() methods and the like are of the singleton design pattern. Basically, there will only ever be one instance of that particular class, and you get it with getInstance().

In this case, LocationProvider will only ever have one instance, since it's device-specific. Instead of creating new instances of it, you can use the shared instance by using the getInstance() method. The singleton pattern is often used in Java when dealing with things like data managers and hardware interfaces, but it shouldn't be used for too much else, since it restricts you to a single instance.