java - 声明一个全局变量,或者在每个类中声明多次

标签 java android class variables

简单的问题。查看我的代码,我注意到我在我的类或方法中多次声明了很多变量...例如:

public Long dbInsertCheckin(final String Class) {
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
...
}

public class SmashDataSource {
    final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    final SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
    final SimpleDateFormat timeFormat = new SimpleDateFormat("HHmm");
...
}

这让我想到,与其声明“dateformat”、“sdf”或“timeformat”或我在多个地方使用的其他格式,不如在我的应用程序类中全局声明这些更有意义,然后引用无论我想去哪里都可以给他们

public class MyApp extends Application {
public final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public final SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
    public final SimpleDateFormat timeFormat = new SimpleDateFormat("HHmm");

并在以后的其他类(class)中这样引用它们:

MyApp.dateformat
Myapp.sdf

从性能/内存使用的角度来看,这会更好吗?有什么理由不这样做吗?对我来说,与最终声明一次相比,多次声明它们似乎会消耗更多内存……但我不知道编译器如何进行优化。

最佳答案

使用全局变量没有错。通常避免使用它们以保持灵 active 和封装性。但是像工厂模式这样的一些设计模式与静态/全局类配合得很好。它还避免了代码重复。

(但是我可能会避免使用我的 Application 类,因此我的全局字段仅在需要时使用,但这是一个实现细节。)

我可能会做这样的事情。它使事情变得灵活,同时将事情放在一个地方,以便它们在您的应用程序中保持一致。

public class MyGlobals
{
    private static SimpleDateFormat dateFormat;


    public static SimpleDateFormat getDateFormat()
    {
        if(dateFormat== null)
        {
            dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
        return dateFormat;

    }
}

然后你可以在其他类中使用它:

MyGlobals.getDateFormat();

====


以下是来自开发文档的一些信息:

http://developer.android.com/guide/faq/framework.html#3

For sharing complex non-persistent user-defined objects for short duration, the following approaches are recommended:

Singleton class

You can take advantage of the fact that your application components run in the same process through the use of a singleton. This is a class that is designed to have only one instance. It has a static method with a name such as getInstance() that returns the instance; the first time this method is called, it creates the global instance. Because all callers get the same instance, they can use this as a point of interaction. For example activity A may retrieve the instance and call setValue(3); later activity B may retrieve the instance and call getValue() to retrieve the last set value.

A public static field/method

An alternate way to make data accessible across Activities/Services is to use public static fields and/or methods. You can access these static fields from any other class in your application. To share an object, the activity which creates your object sets a static field to point to this object and any other activity that wants to use this object just accesses this static field.

A HashMap of WeakReferences to Objects

You can also use a HashMap of WeakReferences to Objects with Long keys. When an activity wants to pass an object to another activity, it simply puts the object in the map and sends the key (which is a unique Long based on a counter or time stamp) to the recipient activity via intent extras. The recipient activity retrieves the object using this key.

Persistent Objects

Even while an application appears to continue running, the system may choose to kill its process and restart it later. If you have data that you need to persist from one activity invocation to the next, you need to represent that data as state that gets saved by an activity when it is informed that it might go away.

For sharing complex persistent user-defined objects, the following approaches are recommended:

Application Preferences
Files
contentProviders
SQLite DB

If the shared data needs to be retained across points where the application process can be killed, then place that data in persistent storage like Application Preferences, SQLite DB, Files or ContentProviders. Please refer to the Data Storage for further details on how to use these components.

关于java - 声明一个全局变量,或者在每个类中声明多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12606700/

相关文章:

java - 我如何在输入 Android EditText 时调用函数

android - 如何减小apk文件的大小?

android - 如何使 map 标记在 Android 上弹跳

java - 返回java中的子类类型

c# - 如何将对象从一个方法初始化为类中的另一个方法?

java - 我如何发现给定日期的季度?

java - Jasper 报告 PDF 不带汉字

java - kafka 获取主题的分区数

android - 服务在真实设备上运行一段时间后停止运行(> 40 分钟),在模拟器上运行

c# - IEquatable是否级联?