如何通过保存方法的返回值来避免对方法的多次调用?

How to avoid several calls to a method by saving its returning value?

我有这个方法

public String getCredentials(String entry) throws IOException {
    KeePassFile database = KeePassDatabase
            .getInstance(config.getProperty("keyPassDataBasePath"))
            .openDatabase(new File(config.getProperty("keyPassKeyPath")));
    Entry sampleEntry = database.getEntryByTitle(entry);
    return sampleEntry.getPassword();
}

这基本上是转到一个 KeePass 数据库,根据其所属帐户的标题检索密码。

有很多方法需要 2 个密码,所以使用 2 个条目。 我不想每次都调用该方法,因为我认为这是一种资源浪费。 如何保存返回值,并在方法需要这些值的其他 类 中使用它?

这行得通吗?反正我觉得这个方法要调用好几次

    private static String pwd1;
    private static String pwd2;

    public void setValues() throws IOException {
        pwd1 = getCredentials("accountName1");
        pwd2 = getCredentials("accountName2");
    }

    public String getPwd1(){
        return pwd1;
    }

    public String getPwd2(){
        return pwd2;
    }

将它们存储在 HasMap 中,密钥为条目,密码为值:

class CachedCredentials {
  private Map<String, String> storedPasswords = new HashMap<>();

  private Properties config;
  
  public CachedCredentials(Properties config) {
     this.config = config;
  }
  
  public String getCredentials(String entry) {
    if (!storedPasswords.containsKey(entry)) {
      KeePassFile database = KeePassDatabase
        .getInstance(config.getProperty("keyPassDataBasePath"))
        .openDatabase(new File(config.getProperty("keyPassKeyPath")));
  
      Entry sampleEntry = database.getEntryByTitle(entry);   
      storedPasswords.put(entry, sampleEntry.getPassword());
    }

    return storedPasswords.get(entry);
  }

然后在您的 setValues 方法中,您可以执行以下操作:

private cachedCreds; //initialize this in your constructor

public void setValues() throws IOException {
    pwd1 = cachedCreds.getCredentials("accountName1");
    pwd2 = cachedCreds.getCredentials("accountName2");
}

如果有人在程序 运行 期间进行内存窥探,此解决方案可能会不安全。可能想想办法通过 base64 编码或实际加密来混淆缓存的密码,但这超出了要求。