我在Application类中的全局变量,实例和单例是否应该是静态的?

时间:2014-03-13 19:30:23

标签: java android

在我的Android应用程序中,我有一个扩展Application类的类,我在那里存储了一些东西。

让我展示一下代码:

public class MyApplication extends Application {

// Custom class to display toasts
public ToastMaker toastMaker = new ToastMaker();

// This class hashes passwords
public HashPassword hashPassword = new HashPassword();

// SQLite Database Handler
public DBTools dbTools;

// Declare the Universal Image Loader for lazy load of images
public ImageLoader imageLoader;

// Fonts
public Typeface font1;
public Typeface font2;

// Photo Handler custom class containing several methods that deal with images
public PhotoHandler photoHandler = new PhotoHandler(this);

// Bitmap Options
public BitmapFactory.Options bitmapOptions;

private static MyApplication singleton;

public MyApplication getInstance() {
    return singleton;
}

@Override
public void onCreate() {
    super.onCreate();
    singleton = this;


    // Setting up fonts
    try {
        font1 = Typeface.createFromAsset(getApplicationContext().getAssets(), C.Fontz.FONT_1);
        font2 = Typeface.createFromAsset(getApplicationContext().getAssets(), C.Fontz.FONT_2);
    } catch (Exception e) {
        e.printStackTrace();
        // Nothing can be done here
    }

    dbTools = DBTools.getInstance(this);

    // Create global configuration and initialize ImageLoader with this configuration
    // https://github.com/nostra13/Android-Universal-Image-Loader
    ImageLoaderConfiguration imageLoaderConfiguration = new ImageLoaderConfiguration.Builder(this).build();
    imageLoader = ImageLoader.getInstance();
    imageLoader.init(imageLoaderConfiguration);

    // Set global bitmap preferences
    bitmapOptions = new BitmapFactory.Options();
    bitmapOptions.inDither = false;
    bitmapOptions.inPurgeable = true;
    bitmapOptions.inInputShareable = true;
    bitmapOptions.inTempStorage = new byte[16 * 1024];


} // End of onCreate

以下是我使用的方法:

public MyApplication myApp;
myApp = (MyApp) getApplication();

然后,让我说我需要一些PhotoHandler类的方法

myApp.photoHandler.handlePhotos();

据我所知,一切正常,但在某处我读到了一些关于那些静态的东西。我对这背后的理论不是很了解,所以我这样做是好还是应该把它们变成静态对象?

3 个答案:

答案 0 :(得分:2)

完全可以保持原状。您不需要声明字段和方法是静态的,因为所有字段和方法都将在Android将管理的单个Application实例中运行。

由于此应用程序已经类似于Singleton,并且由于您正确访问应用程序的方式,因此您不需要:

private static MyApplication singleton;

public MyApplication getInstance() {
    return singleton;
}

答案 1 :(得分:1)

由于getAcpplication()返回您的全局应用程序“对象”,因此您无需在其中创建任何静态内容。

您将在使用

的应用程序中的任何位置获得相同的“全局对象”
myApp = (MyApp) getApplication();

因此不需要静态变量/单例。

答案 2 :(得分:1)

Application类已经是单例,并且保证在应用中的其他所有内容之前调用onCreate()。因此,编写像这样的静态getter非常安全:

public static MyApplication getInstance() {
    return singleton;
}

public static DBTools getDBTools() {
    return singleton.dbTools;
}

唯一的好处是缩短你必须编写的代码,但我看到了一些使用它的流行应用程序(包括谷歌的一个)。