开发者

Should I instantiate a new Facebook variable for each activity, or use static Facebook variable

I have created an abstract class FbActivity, which extends Activity to connect to facebook using Facebook's SDK for Android. Something like the following:

public abstract class FbActivity extends Activity {
  private static final String APP_ID = "xxxxxxxxxxxxx";

  protected Facebook          mFacebook;

  /*
   * Override onCreate to connect to facebook.
   */
  protected void onC开发者_开发技巧reate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mFacebook = new Facebook(APP_ID);
    setFbConnection();
  }

Do I want each FbActivity instantiate their own Facebook variable, or should I make the Facebook variable static, so there is only one variable for the entire application? Or perhaps I should use a singleton type of setup like the following...

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (mFacebook == null) {
      mFacebook = new Facebook(APP_ID);
    }
    setFbConnection();
  }

If you do not have an answer to this exact question, then abstract away from the Facebook variable. When is it "better" to have a static variable (especially in inheritance situations like this)?


Using just one singleton object to store data (obviously) requires less memory than using multiple non-singleton variables. However, access to a static singleton should be synchronized to prevent thread problems, which makes it slightly slower to access. Another pro for singletons might be that they are easier to use in your code (no references to variables that should be passed on), but statics in general can lead to ugly coding practices.

In your case I would use a singleton myself, mainly to limit the number of connections. But note that using singletons is a question of personal preference. Take a look at this post for more discussion on this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜