问题
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 :
- Make
ThisClass
singleton - in this way you will never be able to instantiate more than one class ofThisClass
type. - Create an instance of
ThisClass
type and pass it through constructor to all other classes. - 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 sameThisClass
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