java多个构造方法,Java中构造函数中的多个可选参数 - 构造函数的指数

This is something I've encountered a few times and haven't been able to find a satisfying answer yet. This seems pretty stupid, but after googling this for a while I couldn't come up with something good.

Let's say I have a class with 20 instance variables, each of which is optional (will be initialized or not).

Now I want my constructor(s) to handle all the cases, in case of a few instance variables it's fine and I can just create constructors with different signatures, but here I have 20, so I would need 2^20=1,048,576 constructors to handle all the cases ! That seems ... not very optimal, don't you agree?

So since with this brute force approach I basically have to construct 2^n constructors, where n is the number of instance variables, I want to find a better way to do it.

I've seen a couple solutions for this problem, but I believe they all on assumptions on the data, but in my case each of these variables can be initialized or not at random, I have no way of knowing that before initialization.

I'm looking for some design patterns or ideas that I could apply to make my code a bit more ... maintainable (no don't worry I didn't create 1M+ constructors :)

Thanks.

解决方案

Try the Builder pattern:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值