java 在 Android Studio App 中创建对象的全局实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31055412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 18:00:29  来源:igfitidea点击:

Create a global instance of an object within Android Studio App

javaandroid-studio

提问by Mike James Johnson

I am designing a Game in Android Studio. I have an activity with multiple fragments on it. I also have a Player object that I want to create an instance of.

我正在 Android Studio 中设计游戏。我有一个活动,上面有多个片段。我还有一个要为其创建实例的 Player 对象。

Player player1 = new Player();

All these fragmenets on my activity will be making changes to player1.Instead of passing this object to each Fragment and successive activity with:

我的活动中的所有这些片段都将进行更改,player1.而不是将此对象传递给每个片段和后续活动:

intent.putExtra("Player",player1);

is there a way to access player1 from other fragments and activities without going through the trouble of passing it with the putExtra()method?

有没有办法从其他片段和活动访问 player1 而不用通过putExtra()方法传递它?

I tried making player1 static:

我试着让 player1 静态:

static Player player1 = new Player();

but, i couldnt access player1from other .javaactivity files.

但是,我无法player1从其他.java活动文件访问。

So, basically, I want a strategy to make player1a GLOBAL object that I can reference whenever and wherever. I don't want to make all the methods within the Player class static, because I want to be able to have player1, player2, and player3files on my game, so I need to be able to create an instance of a Player, and I don't think it can be done if every method was static (right?)

所以,基本上,我想要一个策略来制作player1一个我可以随时随地引用的 GLOBAL 对象。我不想让播放器类的静态内的所有方法,因为我希望能有player1player2player3我的游戏文件,所以我需要能够创造的一个实例Player,我不认为如果每个方法都是静态的就可以完成(对吗?)

I just started OOP, so I am sure there's something simple that I am overlooking, or perhaps rather than messing with modifiers there is a better way to achieve what I want. Maybe by using an interface? How would an interface work?

我刚开始使用 OOP,所以我确信我忽略了一些简单的东西,或者也许不是弄乱修饰符,而是有更好的方法来实现我想要的。也许通过使用接口?接口将如何工作?

What about storing info in the Application Object by creating a class that extends Application?

通过创建一个类在应用程序对象中存储信息怎么样extends Application

回答by Ryan J

If you want to access it anywhere, and don't care about privacy, you need to make it public

如果你想在任何地方访问它,并且不关心隐私,你需要让它 public

public static Player player1 = new Player();

The default is package level access only.

默认为仅包级别访问权限。

You can access it by using this syntax in other classes:

您可以通过在其他类中使用此语法来访问它:

Activity1.player1; // do something...

Note: There are likely better design alternatives that simply making a field publicso you can access it anywhere, but that's the bare minimum needed. It's not recommended to do it in this way, and since you're learning, you might want to read up on some of these design concepts.

注意:可能有更好的设计替代方案,只需创建一个字段,public以便您可以在任何地方访问它,但这只是最低要求。不建议以这种方式执行此操作,并且由于您正在学习,因此您可能需要阅读其中的一些设计概念。

Usage of public getters/setters is usually one of the more common ways to access a field of a class/instance, for example.

例如,公共 getter/setter 的使用通常是访问类/实例字段的更常见方法之一。

private static Player player1 = new Player();

public static Player getPlayer1() { return player1; }
public static void setPlayer1(Player p) { player1 = p; }

// ...

So, basically, I want a strategy to make player1 a GLOBAL object that I can reference whenever and wherever. I don't want to make all the methods within the Player class static, because I want to be able to have player1, player2, and player3 files on my game, so I need to be able to create an instance of a Player, and I don't think it can be done if every method was static (right?)

所以,基本上,我想要一种策略,让 player1 成为我可以随时随地引用的 GLOBAL 对象。我不想将 Player 类中的所有方法都设为静态,因为我希望能够在我的游戏中拥有 player1、player2 和 player3 文件,因此我需要能够创建 Player 的实例,并且如果每个方法都是静态的,我认为这是不可能的(对吗?)

No, that's not true. Classes with staticmethods can be instantiated as long as there is a public constructor and/or it's not abstract. staticjust means it's accessed at the classlevel, and does not require an instance, though you can still access staticmethods from an object reference. statichowever also means that allinstances share the same fields, so there is only one field, method, etc. across all instances of the class.

不,那不是真的。static只要有公共构造函数和/或它不是抽象的,就可以实例化带有方法的类。static只是意味着它是在级别访问的,不需要实例,尽管您仍然可以static从对象引用访问方法。static然而也意味着所有实例共享相同的字段,因此在类的所有实例中只有一个字段、方法等。

One design pattern you might consider using is the Singletonpattern, which allows you to get a single instance of a class whenever you need it, so you don't need to mess with static properties and methods (which can have drawbacks if you don't need to use them).

您可能会考虑使用的一种设计模式是Singleton模式,它允许您在需要时获取类的单个实例,因此您不需要弄乱静态属性和方法(如果不这样做可能会有缺点)不需要使用它们)。

What about storing info in the Application Object by creating a class that extends Application?

通过创建一个类在应用程序对象中存储信息怎么样extends Application

According to the documentation, that is an acceptable means, though you might still want to think about some of the overall design choices and determine if that's really the route you want to take.

根据文档,这是一种可以接受的方式,尽管您可能仍想考虑一些整体设计选择并确定这是否真的是您想要采取的路线。

Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's tag, which will cause that class to be instantiated for you when the process for your application/package is created.

需要维护全局应用程序状态的基类。您可以通过在 AndroidManifest.xml 的标记中指定其名称来提供您自己的实现,这将导致在为您的应用程序/包创建进程时为您实例化该类。

回答by Mike James Johnson

in case anyone else was wondering, another solution is to take your class (MyClass.java) add extends Applicationand then go to your android manifest and add a android:namereference:

如果其他人想知道,另一种解决方案是将您的类 ( MyClass.java) 添加extends Application,然后转到您的 android 清单并添加一个android:name引用:

 <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:name="companyname.projectname.MyClass">
        <activity
            android:name=".MyActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

And then when you need to access your object call:

然后当你需要访问你的对象调用时:

Player player = (Player)getApplication();

This will keep the object instance for the entire life of the app. It works, but i like the static method explained above. Also, i am not sure if this is a desirable approach...

这将在应用程序的整个生命周期中保留对象实例。它有效,但我喜欢上面解释的静态方法。另外,我不确定这是否是一种理想的方法......