[英]java configuration/parameter passing design
Often I find the need to engineer objects with configurable functionality. 我经常发现需要设计具有可配置功能的对象。
To exemplify, assume I'm creating a DateIterator
. 举个例子,假设我正在创建一个
DateIterator
。 The configurable option(s) might be whether to iterate the closed interval [start, end]
or the open-end interval [start, end)
. 可配置选项可能是迭代闭合间隔
[start, end]
还是开放端间隔[start, end)
。
new DateIterator(boolean openInterval);
new DateIterator(Interval.OPEN_END);
new DateIterator().openEnd();
new OpenEndedDateIterator();
To this comes a few alternatives which I consider inferior, like integer-based configuration new DateIterator(Interval.OPEN_END);
对于这个,有一些我认为较差的选择,比如基于整数的配置
new DateIterator(Interval.OPEN_END);
or property based configuration. 或基于属性的配置。
Are there any other approaches? 还有其他方法吗? Which approach you do you prefer?
您更喜欢哪种方法?
I'd say the Builder pattern makes sense here: 我会说Builder模式在这里有意义:
DateIterator di =
DateIterator.builder()
.withStartDate(new Date())
.withOpenEnd()
.build();
That way your actual DateIterator can be immutable, while the builder returned by DateIterator.builder()
does the configuration work. 这样你的实际DateIterator可以是不可变的,而
DateIterator.builder()
返回的构建器可以完成配置工作。
While there is no good answer, and it's largely a matter of taste, I do follow the following rule of thumb, with large space for exceptions to avoid over engineering : 虽然没有好的答案,而且主要是品味问题,但我确实遵循以下经验法则,为了避免过度工程,需要大量的例外空间:
Again, these are the rule of thumb I use, in no way mandatory, and often I find myself not respecting them verbatim. 同样,这些是我使用的经验法则,绝不是强制性的,而且我经常发现自己不会逐字尊重它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.