Fragment and factory method

A Fragment must have a constructor with no arguments. That's because Android will call the default constructor to recreate the fragment. If you're not passing in arguments, then you should not need either a constructor or a static factory method (AKA, virtual constructor).


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;
   }
}

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.

http://www.androiddesignpatterns.com/2012/05/using-newinstance-to-instantiate.html

Tags:

Android