2

I have a class with as private List<String> children; which is currently initialized in the constructor but this is not always needed and I want to initialize it only when some other function need it.

The whole point is to rework current implementation without changing to much code.

I know how to do it in other languages, but Java knowledge is quite limited, so far.

4

3 回答 3

4

说清楚,这是实现它的一种方法:

public class Whatever 
{
    private List<String> children;

    public List<String> getChildren
    {
        if ( children == null ) { children = new ArrayList<String>(); }
        return children;
    }
    ...
}

另外,记得写例如。addChild( String child )get'er而言,而不是直接访问该字段。如果你真的很偏执和/或在线程环境中并且创建需要很长时间,你可能想要制作 block synchronized

于 2012-12-10T13:08:21.313 回答
3

如果children为空,您可以在 getter 中创建它。注意正确的同步。如果children创建成本不高,并且您不会创建大量实例,那就急于求成。为您省去麻烦。

于 2012-12-10T13:03:38.503 回答
0

在 java 中,将数据传输对象的成员变量隐藏在访问器方法(臭名昭著的 java bean 的 getter 和 setter)后面是一种常见的做法。如果你这样做,你可以在你的`List getChildren() 方法中添加任何你想要的逻辑(在第一次调用时创建列表,将不可变列表返回给外部客户端等)

于 2012-12-10T13:04:34.583 回答