保持多个类'open'没有(字符串参数[])



我的Java项目中有多个类。

一种是跟踪有多少本书被添加到虚拟图书馆。每次程序使用不同的类时,下次调用簿记员类时,其值将设置回默认值。

我想在main(String args[])实例化每个类 static Example example = new Example();将起作用,然后通过方法传递所有类的参数。

有没有更简单的方法可以做到这一点。

你应该研究一下单例模式。它确保您只有一个对象的实例。

public class BookKeeper{
private static BookKeeper instance;
private BookKeeper{
}
public synchronized static BookKeeper getInstance(){
if(instance == null){
 instance = new BookKeeper();
}
return instance;
}

之后,你调用 BookKeeper.getInstance() 而不是新的 BookKeeper。这将确保您始终具有相同的对象(其中包含数据)

最新更新