please tell me when to use getInstance() method in java. [closed]
Asked Answered
M

3

23

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?

Myronmyrrh answered 7/5, 2012 at 5:52 Comment(2)
This answer is better than the others here.Donato
Actually, the below answer is (arguably) a lot more clear/practical than the top answer linked in the previous comment: #10477781 .Bohannon
F
3

The following code will give you the latitude and longitude. getInstance() will give back the instance of that particular class.

    Criteria myCriteria = new Criteria();
    myCriteria.setCostAllowed(false);
    LocationProvider myLocationProvider = LocationProvider.getInstance(myCriteria);
    Location myLocation = myLocationProvider.getLocation(300);
    latitude  = myLocation.getQualifiedCoordinates().getLatitude();
    longitude = myLocation.getQualifiedCoordinates().getLongitude();
Floris answered 7/5, 2012 at 5:56 Comment(0)
C
38

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.

Chaddie answered 7/5, 2012 at 5:54 Comment(0)
G
4

Method getInstance() is called factory method. It is used for singleton class creation. That means only one instance of that class will be created and others will get reference of that class.

Gristly answered 7/5, 2012 at 5:56 Comment(2)
This is incorrect. For example, Calendar.getInstance() == Calendar.getInstance() is false.Donato
Calendar.getInstance() == Calendar.getInstance() return value depends on getInstance() implementation. If getInstance() returns the same object each time, above equality comparison would return trueCrymotherapy
F
3

The following code will give you the latitude and longitude. getInstance() will give back the instance of that particular class.

    Criteria myCriteria = new Criteria();
    myCriteria.setCostAllowed(false);
    LocationProvider myLocationProvider = LocationProvider.getInstance(myCriteria);
    Location myLocation = myLocationProvider.getLocation(300);
    latitude  = myLocation.getQualifiedCoordinates().getLatitude();
    longitude = myLocation.getQualifiedCoordinates().getLongitude();
Floris answered 7/5, 2012 at 5:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.