Getter Class 内的模式?

Getter Pattern Within Class?

我在 class 中有一个只能从 getter 直接访问的字段。举个例子...

public class CustomerHelper {
  private final Integer customerId;
  private String customerName_ = null;

  public CustomerHelper(Integer customerId) {
    this.customerId = customerId;
  }

  public String getCustomerName() {
    if(customerName_ == null){
      // Get data from database.
      customerName_ = customerDatabase.readCustomerNameFromId(customerId);
      // Maybe do some additional post-processing, like casting to all uppercase.
      customerName_ = customerName_.toUpperCase();
    }
    return customerName_;
  }

  public String getFormattedCustomerInfo() {
    return String.format("%s: %s", customerId, getCustomerName());
  }
}

因此,即使在 class 本身内部,像 getFormattedCustomerInfo 这样的函数也不应该能够通过 customerName_ 访问它。除了提供的 getter 函数之外,是否有办法强制 class 不直接访问字段?

Java中没有这样的机制(或者至少我认为不应该有)。如果您确定应禁止 getFormattedCustomerInfo 直接访问 customerName_,请创建另一个 class 并组合它们。

我会推荐 CustomerInfoFormatter

此外,我会将customerName_更改为customerName,因为该语言通过显式声明支持隐私,不需要添加更多指标。

您似乎正在尝试缓存数据库值,并希望防止访问尚未缓存的值。

如果这是真的,那么变量customerName_不应该存在于CustomerHelperclass中;缓存的值应该靠近数据库。

方法customerDatabase.readCustomerNameFromId(customerId)首先要看一个缓存,如果缓存为空,则调用数据库缓存结果。

实际上,customerName_ 成为缓存中的值:Map<Integer, String> cache,其中键为 customerId