如何处理具有不同参数的构造函数

huangapple go评论96阅读模式
英文:

How to deal with constructor with different arguments

问题

  1. 我创建一个名为Person的类:
  2. public class Person {
  3. private String name; // 姓名
  4. private int age; // 年龄
  5. private int level; // 等级
  6. private int id; // 编号
  7. public Person(String name, int age, int level, int id) {
  8. //...
  9. }
  10. }
  11. 我只能在创建新的Person对象时提供4个参数。但是我希望在没有等级或编号或两者都没有时也能有效。因此,我创建了另外3个构造函数来实现这一点。但是是否有更高效的方法呢?我认为构造函数过多并不好。
英文:
  1. public class Person{
  2. private String name;
  3. private int age;
  4. private int level;
  5. private int id;
  6. public Person(String name, int age, int level, int id){
  7. //...
  8. }
  9. }

I can only have 4 arguments when I create a new Person object. But I want to make it valid when there is no level or id or both. So I created 3 more constructors to do this. But is there any efficient way? I think too many constructors is bad.

答案1

得分: 1

Sure, here's the translation of the provided content:

使用 lombok 的 @Builder 注解

  1. @Builder
  2. public class Person {
  3. private String name;
  4. private int age;
  5. private int level;
  6. private int id;
  7. }

创建

  1. Person.builder().age(1).build();
  2. Person.builder().id(1).age(1).build();
英文:

use lombok @Builder

  1. @Builder
  2. Public Class Person{
  3. private String name;
  4. private int age;
  5. private int level;
  6. private int id;
  7. }

create

  1. Person.builder().age(1).build();
  2. Person.builder().id(1).age(1).build();

答案2

得分: 1

以下是您提供的代码的翻译部分:

  1. 我个人认为类使用多个构造函数没有什么问题但是每种方法都有其利弊
  2. 如果您只想维护一个构造函数并且可以根据需要提供参数那么可能可以使用类似以下的方式
  3. public class Person {
  4. private String name;
  5. private int age;
  6. private int level;
  7. private int id;
  8. /**
  9. * 此构造函数设置为可以提供任意数量的字段参数或不提供任何参数(依赖于设置器)。如果提供了参数,
  10. * 则必须按照以下顺序提供参数:<pre>
  11. *
  12. * <b>Name, Age, Level, ID</b></pre><br>
  13. *
  14. * 不能提供:<b>Name, Level, ID</b>,但是如果要跳过参数,则可以提供:<b>Name, null, Level, ID</b>。
  15. * 如果向参数传递Null或Null字符串(""),则不会更改该参数相关字段的值,并且将应用声明的默认值。
  16. * 以下是此构造函数的有效用法示例:<pre>
  17. *
  18. * Person p = new Person();
  19. * Person p = new Person("John Doe", 34, 366, 1001);
  20. * Person p = new Person("John Doe", 34, 366);
  21. * Person p = new Person("John Doe", 34);
  22. * Person p = new Person("John Doe");
  23. * Person p = new Person("John Doe", null, 366, 1001);
  24. * Person p = new Person(null, null, 366, 1001);
  25. * Person p = new Person("", "", 366, 1001);
  26. * Person p = new Person("", "", 366, null);
  27. * Person p = new Person("John Doe", "34", "366", "1001");
  28. * Person p = new Person("John Doe", "34", "", "1001");
  29. *
  30. * 作为一些示例。</pre>
  31. *
  32. * 你会注意到上面的构造函数示例中,任何一个参数都可以传递一个字符串。在需要整数的地方,可以是整数值的字符串表示形式,
  33. * 只要它们是有效的整数表示形式。如果将任何数值传递给<b>name</b>参数,则会抛出异常。
  34. *
  35. * @param args(可选 - 对象)要提供的可选参数(如果需要)。参数遵循以下输入顺序:<b>Name、Age、Level、ID</b>。
  36. * Name必须是字符串,Age必须是整数或整数的字符串表示形式,Level必须是整数或整数的字符串表示形式,
  37. * ID必须是整数或整数的字符串表示形式。任何参数都可以传递Null或Null字符串(""),
  38. * 在这种情况下,对应参数的相关字段将恢复为其默认值。
  39. */
  40. public Person(Object... args) {
  41. // 构造函数的实现...
  42. }
  43. // 获取器和设置器...
  44. // 重写的toString()方法...
  45. }
  46. **示例构造函数用法**
  47. Person p = new Person("John Doe", 34, 366, 1001);
  48. System.out.println(p.toString());
  49. 阅读构造函数的JavaDoc
英文:

I personally don't see anything wrong with a class utilizing several constructors however there are pro's and con's to everything.

If you want to maintain only a single constructor and optionally supply what you want then perhaps something like this may help:

  1. public class Person {
  2. private String name;
  3. private int age;
  4. private int level;
  5. private int id;
  6. /**
  7. * This constructor is setup so that it can be supplied with any number of
  8. * field arguments or none at all (rely on Setters). If arguments are supplied
  9. * then they &lt;b&gt;must&lt;/b&gt; be supplied is the following order:&lt;pre&gt;
  10. *
  11. * &lt;b&gt;Name, Age, Level, ID&lt;/b&gt;&lt;/pre&gt;&lt;br&gt;
  12. *
  13. * You can not supply: &lt;b&gt;Name, Level, ID&lt;/b&gt; however if you want to skip a
  14. * parameter then you can supply: &lt;b&gt;Name, null, Level, ID&lt;/b&gt;. If a Null or
  15. * a Null String (&quot;&quot;) is supplied to a parameter then the value for that field
  16. * the parameter is related to is not changed and the declared default would
  17. * apply to it. The following would be a valid uses of this constructor:&lt;pre&gt;
  18. *
  19. * Person p = new Person();
  20. * Person p = new Person(&quot;John Doe&quot;, 34, 366, 1001);
  21. * Person p = new Person(&quot;John Doe&quot;, 34, 366);
  22. * Person p = new Person(&quot;John Doe&quot;, 34);
  23. * Person p = new Person(&quot;John Doe&quot;);
  24. * Person p = new Person(&quot;John Doe&quot;, null, 366, 1001);
  25. * Person p = new Person(null, null, 366, 1001);
  26. * Person p = new Person(&quot;&quot;, &quot;&quot;, 366, 1001);
  27. * Person p = new Person(&quot;&quot;, &quot;&quot;, 366, null);
  28. * Person p = new Person(&quot;John Doe&quot;, &quot;34&quot;, &quot;366&quot;, &quot;1001&quot;);
  29. * Person p = new Person(&quot;John Doe&quot;, &quot;34&quot;, &quot;&quot;, &quot;1001&quot;);
  30. *
  31. * as some examples.&lt;/pre&gt;
  32. *
  33. * You will of noticed in the constructor examples above that any one the parameters can
  34. * be supplied a string. Where Integers are required there can be string representations
  35. * of integer values...as long as they are valid integer representations. If the a
  36. * any numerical value is supplied to the &lt;b&gt;name&lt;/b&gt; parameter then an exception is
  37. * thrown.
  38. *
  39. * @param args (Optional - Object) The optional parameters to be supplied if desired.
  40. * The parameters follow this entry order: &lt;b&gt;Name, Age, Level, ID&lt;/b&gt;. Name must be
  41. * a string, Age must be Integer or a string representation of an Integer, Level must
  42. * be Integer or a string representation of an Integer, ID must be Integer or a string
  43. * representation of an Integer. Any parameter can be passed a Null or a Null String (&quot;&quot;)
  44. * in which case that corresponding parameter&#39;s related field will fall to its default
  45. * value.
  46. */
  47. public Person(Object... args) {
  48. if (args.length &gt; 0) {
  49. String invalidString = &quot;Person Class Constructor Error - &quot;
  50. + &quot;Invalid Argument Supplied! (&quot; + java.util.Arrays.toString(args)
  51. .replaceAll(&quot;[\\[\\]]&quot;, &quot;&quot;) + &quot;)&quot;;
  52. try {
  53. // Name parameter...
  54. if (args.length &gt;= 1 &amp;&amp; args[0] != null &amp;&amp; !args[0].toString().equals(&quot;&quot;)) {
  55. if (args[0].toString().matches(&quot;\\D+&quot;)) {
  56. this.name = args[0].toString();
  57. }
  58. else {
  59. throw new Exception(&quot;Not a proper String for Name field! &quot;
  60. + &quot;It contains digits!&quot;);
  61. }
  62. }
  63. // Age parameter...
  64. if (args.length &gt;= 2 &amp;&amp; args[1] != null &amp;&amp; !args[1].toString().equals(&quot;&quot;)) {
  65. if (args[1].toString().matches(&quot;\\d{1,3}&quot;)) {
  66. if (args[1] instanceof String &amp;&amp; !args[1].toString().equals(&quot;&quot;)) {
  67. args[1] = Integer.valueOf(args[1].toString());
  68. }
  69. if (!args[1].toString().equals(&quot;&quot;)) {
  70. this.age = (int) args[1];
  71. }
  72. }
  73. else {
  74. throw new Exception(&quot;Not a proper Integer value for Age field!&quot;);
  75. }
  76. }
  77. // Level parameter...
  78. if (args.length &gt;= 3 &amp;&amp; args[2] != null &amp;&amp; !args[2].toString().equals(&quot;&quot;)) {
  79. if (args[2].toString().matches(&quot;\\d+&quot;)) {
  80. if (args[2] instanceof String &amp;&amp; !args[2].toString().equals(&quot;&quot;)) {
  81. args[2] = Integer.valueOf(args[2].toString());
  82. }
  83. if (!args[2].toString().equals(&quot;&quot;)) {
  84. this.level = (int) args[2];
  85. }
  86. }
  87. else {
  88. throw new Exception(&quot;Not a proper Integer value for Level field!&quot;);
  89. }
  90. }
  91. // ID parameter...
  92. if (args.length &gt;= 4 &amp;&amp; args[3] != null &amp;&amp; !args[3].toString().equals(&quot;&quot;)) {
  93. if (args[3].toString().matches(&quot;\\d+&quot;)) {
  94. if (args[3] instanceof String &amp;&amp; !args[3].toString().equals(&quot;&quot;)) {
  95. args[3] = Integer.valueOf(args[3].toString());
  96. }
  97. if (!args[3].toString().equals(&quot;&quot;)) {
  98. this.id = (int) args[3];
  99. }
  100. }
  101. else {
  102. throw new Exception(&quot;Not a proper Integer value for ID field!&quot;);
  103. }
  104. }
  105. }
  106. catch (Exception ex) {
  107. System.err.println(invalidString);
  108. System.err.println(ex.toString());
  109. // Close Application!
  110. // Do whatever you like on a Constructor Failure.
  111. System.exit(0);
  112. }
  113. }
  114. }
  115. // GETTERS and SETTERS
  116. public String getName() {
  117. return name;
  118. }
  119. public void setName(String name) {
  120. this.name = name;
  121. }
  122. public int getAge() {
  123. return age;
  124. }
  125. public void setAge(int age) {
  126. this.age = age;
  127. }
  128. public int getLevel() {
  129. return level;
  130. }
  131. public void setLevel(int level) {
  132. this.level = level;
  133. }
  134. public int getId() {
  135. return id;
  136. }
  137. public void setId(int id) {
  138. this.id = id;
  139. }
  140. // An overriden toString() method
  141. @Override
  142. public String toString() {
  143. return new StringBuilder(&quot;&quot;).append(&quot;Name = &quot;).append(name).append(&quot;, Age = &quot;)
  144. .append(age).append(&quot;, Level = &quot;).append(level).append(&quot;, ID = &quot;)
  145. .append(id).toString();
  146. }
  147. }

Example Constructor Usage:

  1. Person p = new Person(&quot;John Doe&quot;, 34, 366, 1001);
  2. System.out.println(p.toString());

Read the Constructor's JavaDoc.

huangapple
  • 本文由 发表于 2020年6月29日 10:27:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/62630343.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定