课堂上的吸气模式?

时间:2018-05-03 00:20:24

标签: java private encapsulation getter

我在类中有一个字段,只能直接从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());
  }
}

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

2 个答案:

答案 0 :(得分:2)

Java中没有这样的机制(或者至少我认为不应该这样)。如果您确定{... 1}}应禁止直接访问sharey='all',请创建另一个类并撰写它们。

我建议getFormattedCustomerInfo

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

答案 1 :(得分:1)

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

如果这是真的,则变量customerName_不应存在于CustomerHelper类中;缓存的值应该更靠近数据库。

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

有效地,customerName_成为缓存中的值:Map<Integer, String> cache,其中密钥为customerId