如何在Java中的不同类之间共享数据

Java中的各个类之间共享数据的最佳方法是什么?我有一堆变量,它们由不同的类以不同的方式在不同的文件中使用。让我尝试说明问题的简化版本:

这是我之前的代码:

public class Top_Level_Class(){

int x, y;

// gets user input which changes x, y;

public void main(){

int p, q, r, s;

// compute p, q, r, s

doA(p,q,r);

doB(q,r,s);

}

public void doA(int p, int q, int r){

// do something that requires x,y and p, q, r

}

public void doB(int q, int r, int s){

// does something else that requires x, y and q, r, s

}

}

现在看起来像这样:

public class Top_Level_Class(){

int x, y;

SomeClass1a a = new SomeClass1a();

SomeClass1a b = new SomeClass1b();

// gets user input which changes x, y;

public void main(){

int p, q, r, s;

// compute p, q, r, s

a.doA(p,q,r);

b.doB(q,r,s);

}

public class SomeClass1a() { // in its own separate file

public void doA(int p, int q, int r){

// do something that requires x,y and p, q, r

}

}

public class SomeClass1b() { // in its own separate file

public void doB(int q, int r, int s){

// does something else that requires x, y and q, r, s

}

}

所以无论如何,我应该每次都传递x和y(其中x,y是存储在辅助类func中的变量)吗?

 a.set(x,y);

a.doA(p,q,r);

我的想法是要有一个特殊的容器类,其中存放x和y。顶级类将具有容器类的实例,并使用set方法更改x,y。

// in the top level class:

Container c = new Container(x,y);

a.setContainer(c);

b.setContainer(c);

我的帮助程序类还将具有该容器的一个实例,它将指向与顶层相同的实例。这样,他们将访问与顶层相同的x,y。

我想知道我是否应该

  • 使用容器类
  • 每次将x,y加载到子类中
  • ?? 一些更好的方法

回答:

我想您问题的答案是称为Singleton的设计模式。基本上,它允许您随时在系统中获取和利用类的相同(和唯一)实例。

这是它的实现(请原谅可能的语法错误,我没有对其进行编译):

class Container{

//eventually provides setters and getters

public float x;

public float y;

//------------

private static Container instance = null;

private void Container(){

}

public static Container getInstance(){

if(instance==null){

instance = new Container();

}

return instance;

}

}

然后,如果您在代码的其他位置导入了容器,则可以编写例如

Container.getInstance().x = 3;

temp = Container.getInstance().x;

您将影响系统中唯一容器实例的属性

但是,在许多情况下,最好使用“依赖注入”模式,因为它可以减少不同组件之间的耦合。

以上是 如何在Java中的不同类之间共享数据 的全部内容, 来源链接: utcz.com/qa/426277.html

回到顶部