Creating one instance of an object and using the same instance in different class files

折月煮酒 提交于 2019-12-25 16:07:45

问题


I have been searching around the internet about Creating an instance of a object in one class and using that same instance in a different class. I have not found any posts though that apply to what I want to do. Here is an example of what I want to do.


public class ThisClass{
  public ThisClass{
    //This is the object I want to create
  }
}

public class FirstClass{
  public ThisClass thisclass = new ThisClass();
}

public class SecondClass{
  //Now in SecondClass I want to be able to access the instance of ThisClass
  //I created in FirstClass
}

Any ideas on what to do here that wont be too complex and make the code a nightmare to look at?


回答1:


Three solutions came into my mind :

  1. Make ThisClass singleton - in this way you will never be able to instantiate more than one class of ThisClass type.
  2. Create an instance of ThisClass type and pass it through constructor to all other classes.
  3. Create an abstract class / interface which holds a static instance variable of type ThisClass, and then extend/implement this abstract class / interface in classes you want to have the same ThisClass instance.



回答2:


Here's one way:

public class ThisClass {
    public ThisClass() {
        // This is the object I want to create
    }
}

public class FirstClass {
    private ThisClass thisClass = new ThisClass();

    public ThisClass getThisClass() {
        return thisClass;
    }

}

public class SecondClass {
    //Now in SecondClass I want to be able to access the instance of ThisClass
    //I created in FirstClass
    private ThisClass thisClass;

    public SecondClass(ThisClass thisClass) {
        this.thisClass = thisClass;
    }
}

public class ThirdClass {
    public ThirdClass() {
        new SecondClass(new FirstClass().getThisClass());
    }
}


来源:https://stackoverflow.com/questions/23460554/creating-one-instance-of-an-object-and-using-the-same-instance-in-different-clas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!