How to share data between separate classes in Java

后端 未结 4 952
面向向阳花
面向向阳花 2020-12-29 12:44

What is the best way to share data between separate classes in Java? I have a bunch of variables that are used by different classes in separate files in different ways. Let

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-29 13:05

    I guess the answer to your question is the Design Pattern called Singleton. It basically allows you to get and exploits the same (and unique) instance of a class whenever you want in your system.

    This is its implementation (please forgive possible syntax errors, I did not compile it):

    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;
      }
    }
    

    then if elsewhere in your code you import the Container you can write for example

    Container.getInstance().x = 3;
    temp = Container.getInstance().x;
    

    and you will affect the attributes of the unique container instance you have in your system

    In many cases it is however better to use the Dependency Injection pattern as it reduces the coupling between different components.

提交回复
热议问题