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

问题描述

我有这种方法

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编码或实际上对其进行加密来混淆高速缓存密码的方法,但这超出了要求。