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

f20*_*20k 9 java oop class-design

在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
    }
}
Run Code Online (Sandbox Code Playgroud)

现在它看起来像这样:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

 a.set(x,y);
 a.doA(p,q,r);
Run Code Online (Sandbox Code Playgroud)

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

// in the top level class:
Container c = new Container(x,y);
a.setContainer(c);
b.setContainer(c);
Run Code Online (Sandbox Code Playgroud)

我的帮助器类也有一个容器实例,它指向与顶层相同的实例.这样他们就可以访问与顶层相同的x,y.

我想知道我是否应该

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

Sin*_*ico 13

我想你的问题的答案是名为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;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后,如果您的代码中的其他地方导入了Container,您可以编写例如

Container.getInstance().x = 3;
temp = Container.getInstance().x;
Run Code Online (Sandbox Code Playgroud)

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

但是,在许多情况下,使用依赖注入模式会更好,因为它会减少不同组件之间的耦合.