在java中访问方法和变量
基本上,在我的应用程序中,我有一个名为Resources的类,我在这个类中创建并保存我的所有对象 当我创建一个对象(我们称之为myObject)时,我需要能够访问资源类中的各种方法和/或变量,因此目前,我正在执行以下操作:在java中访问方法和变量,java,class,constructor,reference,Java,Class,Constructor,Reference,基本上,在我的应用程序中,我有一个名为Resources的类,我在这个类中创建并保存我的所有对象 当我创建一个对象(我们称之为myObject)时,我需要能够访问资源类中的各种方法和/或变量,因此目前,我正在执行以下操作: public class Resources { int height; //This will hold the height of the current device's screen (in pixels). For the purpose of thi
public class Resources {
int height; //This will hold the height of the current device's screen (in pixels). For the purpose of this question, please assume this has been intialised at some point.
public void createObjects(){
MyObject myObject = new MyObject(this); //Pass reference to this (Resources) class into constructor
}
public void method1(){
//Do something here, this method could do some work or could be a proxy method to another class
}
}
所以我的“MyObject”类看起来是这样的:
public class MyObject{
Resources resources;
int yPosition;
public MyObject(Resources resources){
this.resources = resources;
}
public intialise(){
//Some examples
resources.method1();
yPosition = (resources.height)/2;
}
}
正如我所说,我的Resources类就是这样——它保存了我的所有对象和其他重要信息(如屏幕大小等),因此我需要从我创建的对象中访问这个类(这样我就可以将与该对象相关的所有代码保存在对象本身中,而不是外部)(例如,直接在Resources类中,这将非常混乱)
我一直在这样做,但并没有引起任何问题,我意识到我只是在传递对我的“资源”对象的引用,我想知道的是,这是一种“可接受”的方式来访问我需要的内容吗?这类问题更适合网站。他们喜欢讨论使用工厂而不是显式的构造函数nd所有这些东西。@PM77-1这是我们称之为示例代码的东西,我们不想“讨论”。这在代码审查中是离题的。@SimonAndréForsberg-这很有意思。你有什么建议吗?我的建议是在代码审查中发布真正的代码,并要求对其进行审查。代码审查用户在面对具有真实上下文的真正代码时,可能会提出更好的做法。以及当他们这样做的时候,他们可能会发现其他可以改进的东西。