java怎么设置变量,如何在Java中仅设置一次变量

I need to implement a class in java where its field needs to be set only once, but it's value is not known at field declaration. To do so I have:

public class MyClass {

private String field1 = null;

public void setField1(String value) {

if (field1 == null) {

field1 = value;

}

}

}

However what I have do not prevent users to call setField1 more than once. That may lead to confusion where a user is trying to set it (without knowing it has been set somewhere else) and then the user will get confused by the field1 is not giving the value they set - until they go into the setField1 method to see what happened.

The other solution that I don't like is make a constructor to take into the value of field1, and then provide no setter. Because it makes the class a lot harder to be extended, when multiple String fields are needed - in this approach, the constructor will need to take in a couple String as parameters, and then the user can be so easily confused by/missing the parameters.

And apparently setting field1 as final won't work either.

What should I do to prevent the issue I mentioned above?

解决方案

You should generally use the builder pattern for cases like this: https://en.wikipedia.org/wiki/Builder_pattern

MyClass instance = (new MyClassBuilder())

.setField1(...)

.setField2(...)

.build();

Your builder object lets you set all the fields and options you like, but the MyClass instance that it builds does not.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值