如何在Java中仅设置一次变量 [英] How to allow variables being set only once in java

查看:328
本文介绍了如何在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;
        }
     }
}

但是,我所拥有的并不能阻止用户多次呼叫setField1.这可能会导致在用户尝试进行设置(不知道它已在其他位置设置)的情况下造成混乱,然后用户会感到困惑,因为field1没有给出他们设置的值-直到他们进入看看发生了什么的方法.

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.

我不喜欢的另一种解决方案是使构造函数使用field1的值,然后不提供设置器.因为它使类很难扩展,所以当需要多个String字段时-在这种方法中,构造函数将需要使用几个String作为参数,然后用户很容易被/忽略.参数.

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.

并且显然将field1设置为final也不起作用.

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

我应该怎么做才能防止上述问题?

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

推荐答案

对于以下情况,通常应使用构建器模式: https://en.wikipedia.org/wiki/Builder_pattern

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();

您的构建器对象使您可以设置自己喜欢的所有字段和选项,但它构建的MyClass实例却不能.

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

这篇关于如何在Java中仅设置一次变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆