Reputation: 3014
So I am diving head first into Android development and want to do some stuff with the bluetooth API. What's confusing me is that in every example I've seen you don't need to create a new instance of the a bluetooth adapter, you can just call it like so.
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
I can't wrap my mind around why nobody does something this:
BluetoothAdapter mBluetoothAdapter = new BluetoothAdapter();
myBluetoothAdapter = mBluetoothAdapter.getDefaultAdapter();
This is now leaving me very confused with what classes I have to create a new instance of and what objects I don't.
Upvotes: 1
Views: 548
Reputation: 1767
This is a singleton design pattern. You use this pattern when you just want one instance of that class. You don't want multiple instances of a BluetoothAdapter. You usually want to use a singleton when you have to share resources between the instances, for example you might want to use class over multiple objects. How this is done in java is through a static field, something like this:
class BluetoothAdapter{
private static adapter = null;
private BluetoothAdapter(){
}
public static getDefaultAdapter(){
if (adapter == null){
adapter = new BluetoothAdapter();
}
return adapter;
}
}
First of all this allows you to have only one instance of this object at the time. Additionally, it only creates the object when you actually need it. If you never call getDefaultAdapter(), the adapter will never be created.
Upvotes: 0
Reputation: 2217
If you are going get an object from a factory, why would you want to initialize an object at all? You are essentially creating two objects and then throwing away the first one. So, just skip the object initialization line if your class has a factory method. And yeah the only way to know if a class has a factory method or not is by looking at documentation and learning as you go.
Upvotes: 0
Reputation: 1564
The BluetoothAdapter class is probaly a Singleton class, so you can get the instance by calling the static method getDefaultAdapter() and that method returns an instance for you.
And you cannot instantiate a static class.
Take a look at this wikipedia page: http://en.wikipedia.org/wiki/Singleton_pattern
Upvotes: 1