我正在用 JGit 做一些东西
情况是这样的。
用户将打开一个 git 存储库并以各种方式使用它。
在程序中这个存储库在Repository 类中有信息,各种函数将通过调用它来访问这个存储库。这个存储库最初是由构建器构建的。
FileRepositoryBuilder builder = new FileRepositoryBuilder();
Repository repository = builder.setGitDir(new File(repodir))
.readEnvironment() // scan environment GIT_* variables
.findGitDir() // scan up the file system tree
.build();
在制作程序时,我想我应该保持这个存储库打开并在整个程序中可用。我有一个想法来创建一个这样的类来保留当前打开的存储库
public class CurrentRepo{
private static Repository repository;
public static Repository getRepository(){
return this.repository;
}
public static void setRepository(Repository repository){
this.repository = repository;
}
}
之后我会调用
CurrentRepo.getRepository()
获取打开的版本库信息。
这会导致问题吗?这是一种糟糕的方式吗?
有没有更好的解决方案?
最佳答案
一般来说,我会说使用静态字段来存储这样的信息是可以的。但是,正如你所说的
I should keep this repository opened and usable through the program
最基本的问题是:您是否有可能在同一 JVM 中运行多个程序实例并打开不同的存储库?如果是这种情况,您应该避免使用静态字段(也称为全局变量)来存储此信息。尝试在您的程序中确定一个类,该类可以将您的信息存储为程序状态的一部分,该状态与程序一样长,而不是与 JVM 一样长。您仍然可以使用像 CurrentRepo
这样的类,它包含当前打开的存储库中的所有信息,但您不应将此信息存储在静态字段中。
关于java - 在 Java 程序上保留一个类是一个好方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25000404/