2015年8月27日 星期四

使用newInstance來初始化Fragment (Android的一百種奇技淫巧)

原文出處:Using newInstance() to Instantiate a Fragment

問題: 使用new MyFragment()MyFragment.newInstance() 有什麼不同?哪個比較好?
答: 使用newInstance()比較好,兩個原因:
1. 方便使用者使用。
2. 
通過強制宣告一個static factory method去迫使使用者提供良好定義的行為,
並能同時確保使用者免受錯誤的初始化時機,使用者不再需要擔心不小心忘了初始化的參數或錯誤的使用。
I recently came across an interesting question on StackOverflow regarding Fragment instantiation:
What is the difference between new MyFragment() andMyFragment.newInstance()? Should I prefer one over the other?
Good question. The answer, as the title of this blog suggests, is a matter of proper design. In this case, the newInstance() method is a "static factory method," allowing 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. For example, consider the following code:
public class MyFragment extends Fragment {

    /**
     * Static factory method that takes an int parameter,
     * initializes the fragment's arguments, and returns the
     * new fragment to the client.
     */
    public static MyFragment newInstance(int index) {
        MyFragment f = new MyFragment();
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);
        return f;
    }

}
Rather than having the client call the default constructor and manually set the fragment's arguments themselves, we provide a static factory method that does this for them. This is preferred over the default constructor for two reasons. One, it's convenient for the client, and two, it enforces well-defined behavior. By providing a static factory method, we protect ourselves from bugs down the line—we no longer need to worry about accidentally forgetting to initialize the fragment's arguments or incorrectly doing so.
Overall, while the difference between the two is mostly just a matter of design, this difference is really important because it provides another level of abstraction and makes code a lot easier to understand.
Feel free to leave a comment if this blog post helped (it will motivate me to write more in the future)! :)

沒有留言:

張貼留言

有任何疑問歡迎寄信給我,
但垃圾訊息我會刪光喔!