gkovalechyn gkovalechyn - 1 month ago 6
Java Question

Best way to share updated data between classes in java

I am working on a projects and I have run into a problem, I don't know the best way to share updated data between classes. The current way that I am doing this is by having a static instance of my class in it and having all the other classes change the instance and not the original class.

public class A{
public static volatile instance;
public B b = new B();
public C c = new C();
public D d = new D();
public A(){
this.instance = this;
b.changeData();
}
}

public class B{
public void changeData(){
A.instance.d.changeSomethingInD();
}
}


Now, all the changes that D made to its variables can be accessed by B and C. Is there a better way to do this?

Edit 1: The problem that I have is having updated variables accessible to all the other classes. This was what I was doing before:

public class MainClass extends JavaPlugin{
private RegionLoader rLoader;
private ClassesLoader cLoader;
private MessageHandler mHandler;
private PlayerDates pDates;

public MainClass(){

dirMaker();

mHandler = new MessageHandler(this);
pDates = new PlayerDates(this);
cLoader = new ClassesLoader(this);
rLoader = new RegionLoader(this);

}
//getters and setters
}


But the problem is if the RegionLoader changes somithing within itself, the ClassesLoader won't have the updated variables and will work with the old ones, or would it?

Answer

Why not just pass A into the constructor of B. This way you wouldn't need to use static data.

   public class A{

      public B b;
      public C c = new C();
      public D d = new D();

      public A(){
         b = new B(this);
         b.changeData();
      }
    }

    public class B{
      private A a;

      public B(A a){
         this.a = a;
      }
      public void changeData(){
         a.d.changeSomethingInD();
      }
    }

You could also checkout the observer pattern.