我是一个非常新的编程,想要知道我是否能以某种方式从我已经习惯new MyClass();
在另一个类中使用它的类中获取对象,并且我不需要new MyClass();
再次使用它.希望你明白这一点.
一些非常简单的例子:
class MyFirstClass
{
Something st = new Something();
}
class Something()
{
// some code
}
class MySecondClass
{
// This is where I want to use the object from class Something()
// like
getObjectFromClass()
}
Run Code Online (Sandbox Code Playgroud)
您可以使用单例模式来实现这一点
这是此类对象的启动示例。它有一个私有构造函数和公共类方法 getInstance
:
静态方法,在其声明中具有 static 修饰符,应使用类名调用,而不需要创建该类的实例
当我们调用getInstance
它时,它会检查一个对象是否已创建,并将返回已创建对象的实例,如果尚未创建,它将创建一个新对象并返回它。
public class SingletonObject {
private static int instantiationCounter = 0; //we use this class variable to count how many times this object was instantiated
private static volatile SingletonObject instance;
private SingletonObject() {
instantiationCounter++;
}
public static SingletonObject getInstance() {
if (instance == null ) {
instance = new SingletonObject();
}
return instance;
}
public int getInstantiationCounter(){
return instantiationCounter;
}
}
Run Code Online (Sandbox Code Playgroud)
要检查它是如何工作的,您可以使用以下代码:
public static void main(String[] args) {
SingletonObject object = SingletonObject.getInstance();
System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");
object = SingletonObject.getInstance();
System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");
object = SingletonObject.getInstance();
System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");
}
Run Code Online (Sandbox Code Playgroud)