What is the aim of using a Factory to construct our fragments? Android Studio provides some boilerplate code generation, and provides the factory method when creating a fragment.
So what is the purpose of that? What is the gain?
Static factory methods allow us to initialize and setup a new Fragment without having to call its constructor and additional setter methods. Providing static factory methods for your fragments is good practice because it encapsulates and abstracts the steps required to setup the object from the client.
According to the Android documentation, a fragment is a part of applications user interface that is bound to an activity. Fragments have their lifecycle and layouts or UI components. Fragments help enrich your UI design, pass data between different screens, and adapt to different device configurations.
A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class for creating an object but let the subclasses decide which class to instantiate. In other words, subclasses are responsible to create the instance of the class.
This class was deprecated in API level 28. Use the Support Library DialogFragment for consistent behavior across all devices and access to Lifecycle. This class was deprecated in API level 28.
Using static factory method is not just for the fragment, I use it to create intent, adapter and other classes as well. By this approach you simply have the control of the object creation.
One of the good advantage is you simply increase the cohesion by encapsulating bundle keys.
class FragmentFoo extends Fragment{
}
When you want to send a bundle to this fragment from outside
// Activity Foo
Bundle bundle = new Bundle();
bundle.putString("name","Foo");
Fragment fragment = new FragmentFoo();
fragment.setArgs(bundle);
To extract this name, you need to use "name" key in fragment as well, if you use it as hardcoded, you may have some errors,typos. So you can use a constant in order to make sure you don't make typo. But in this case you need to put it somewhere both can see it. Some creates another class in order to keep all contants which is very ugly and hard to maintain, some puts the keys in the fragment and make it public and use it everywhere,
by static factory method, you can simply keep everything in fragment and no need to expose. Whoever needs to use this fragment will have a clear idea what it requires and also will not need to know what keys are. Just send the required params will be enough for them.
class FragmentFoo extends Fragment{
private static final String KEY_NAME = "name";
private String name;
public static Fragment newInstance(String name){
Bundle bundle = new Bundle();
bundle.putString(KEY_NAME, "name");
Fragment fragment = new FragmentFoo();
fragment.setArgs(bundle);
return fragment;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With