Java中构造函数中的多个可选参数 - 构造函数的指数 [英] Multiple optional arguments in constructor in Java - exponential number of constructors

查看:684
本文介绍了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.

假设我有一个包含20个实例变量的类,每个变量这是可选的(将被初始化或不被初始化)。

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

现在我希望我的构造函数处理所有情况,如果有一些实例变量它很好并且我可以创建具有不同签名的构造函数,但是这里我有20个,所以我需要 2 ^ 20 = 1,048,576 构造函数来处理所有情况!这似乎......不是非常优化,你不同意吗?

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?

所以,由于采用这种强力方法,我基本上必须构造2 ^ n个构造函数,其中n是实例变量的数量,我想找到一个更好的方法来实现它。

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.

我正在寻找一些设计模式或想法,我可以应用于使我的代码更多...可维护(不要担心我没有创建1M +构造函数:)。

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 :)

谢谢。

推荐答案

尝试使用构建器模式:

http://rwhansen.blogspot.com/2007/07/theres- builder-pattern-that-joshua.html

这篇关于Java中构造函数中的多个可选参数 - 构造函数的指数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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