java配置/参数传递设计
我经常发现需要设计具有可配置功能的对象。
举例来说,假设我正在创建一个 DateIterator。可配置的选项可能是迭代闭区间 [start, end]
还是开放区间 [start, end)
。
- (1) 在我看来,不优雅的解决方案 - 仅限于一个 true/false 配置选项
new DateIterator(boolean openInterval);
- (2) 类型安全枚举方式 - 通常有点笨重
new DateIterator(Interval.OPEN_END);
- (3) 非常规的尝试 - 不错,但不是太直接了
new DateIterator().openEnd();
- (4) 继承方法 - 经常过度设计
new OpenEndedDateIterator();
为此,有一些我认为较差的替代方案,例如基于整数的配置 new DateIterator(Interval.OPEN_END);
或基于属性的配置。
还有其他方法吗?您更喜欢哪种方法?
Often I find the need to engineer objects with configurable functionality.
To exemplify, assume I'm creating a DateIterator
. The configurable option(s) might be whether to iterate the closed interval [start, end]
or the open-end interval [start, end)
.
- (1) The, in my opinion, ungraceful solution - limited to only one true/false configuration option
new DateIterator(boolean openInterval);
- (2) The typesafe enum way - typically a bit bulky
new DateIterator(Interval.OPEN_END);
- (3) The unconventional attempt - nice but not too straight forward
new DateIterator().openEnd();
- (4) The inheritance approach - often over-engineering
new OpenEndedDateIterator();
To this comes a few alternatives which I consider inferior, like integer-based configuration new DateIterator(Interval.OPEN_END);
or property based configuration.
Are there any other approaches? Which approach you do you prefer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想说 Builder 模式在这里是有意义的:
这样您的实际 DateIterator 可以是不可变的,而由
DateIterator.builder()
返回的构建器完成配置工作。I'd say the Builder pattern makes sense here:
That way your actual DateIterator can be immutable, while the builder returned by
DateIterator.builder()
does the configuration work.虽然没有好的答案,而且这在很大程度上是一个品味问题,但我确实遵循以下经验法则,并留有很大的例外空间,以避免过度工程:
再说一次,这些是我使用的经验法则,绝不是强制性的,而且我经常发现自己没有逐字尊重它们。
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.