gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:23:23 25 4
gpt4 key购买 nike

在我的 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();

据我所知,一切正常,但我在某处读到一些关于静态的内容。我不太了解这背后的理论,所以我可以这样做还是应该将它们设为静态对象?

最佳答案

让它保持原样是完全可以的。您不需要将字段和方法声明为静态,因为它们都将在 Android 管理的单个应用程序实例中运行。

由于此应用程序已经类似于单例,并且由于您访问应用程序的方式(正确),您不需要这样:

private static MyApplication singleton;

public MyApplication getInstance() {
return singleton;
}

关于java - 我在 Application 类中的全局变量、实例和单例是否应该是静态的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22389004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com