在Java构造函数中有许多参数。
在Java构造函数中有许多参数。
我是一个Java初学者。\n在我的图书馆程序中,像这样创建带有多个参数的构造函数是一个好方法吗?\n
public class Book implements Serializable { private String title; private String directorName; private String directorSurname; private String type; private int issueYear; private ListactorNames; private List actorSurnames; private Tuple directorFullName; public Book(String title, String directorName, String directorSurname, String type, int issueYear, List actorNames, List actorSurnames, Tuple directorFullName){ this.title = title; this.directorName = directorName; this.directorSurname = directorSurname; this.type = type; this.issueYear = issueYear; this.actorNames = actorNames; this.actorSurnames = actorSurnames; this.directorFullName = directorFullName; }
\n还是有更好的方法来创建这样的构造函数吗?
在Java中创建一个具有超过3个参数的构造函数不是最佳实践。因为您需要知道每个参数的顺序。我可以建议您在类的title字段中使用getter和setter的方式:
public String getTitle() { return title; } public Book setTitle(String title) { this.title = title; return this; }
通过这种结构,您可以在创建新实例的同时创建一个非常漂亮的构造:
Book book = new Book() .setTitle("Book") .setType("Comedy") .setActorNames(Arrays.asList("Abzal"));
您的类的完整重构版本:
public class Book implements Serializable { private String title; private String directorName; private String directorSurname; private String type; private int issueYear; private ListactorNames; private List actorSurnames; private Tuple directorFullName; public Book() { } public String getTitle() { return title; } public Book setTitle(String title) { this.title = title; return this; } public String getDirectorName() { return directorName; } public Book setDirectorName(String directorName) { this.directorName = directorName; return this; } public String getDirectorSurname() { return directorSurname; } public Book setDirectorSurname(String directorSurname) { this.directorSurname = directorSurname; return this; } public String getType() { return type; } public Book setType(String type) { this.type = type; return this; } public int getIssueYear() { return issueYear; } public Book setIssueYear(int issueYear) { this.issueYear = issueYear; return this; } public List getActorNames() { return actorNames; } public Book setActorNames(List actorNames) { this.actorNames = actorNames; return this; } public List getActorSurnames() { return actorSurnames; } public Book setActorSurnames(List actorSurnames) { this.actorSurnames = actorSurnames; return this; } public Tuple getDirectorFullName() { return directorFullName; } public Book setDirectorFullName(Tuple directorFullName) { this.directorFullName = directorFullName; return this; } }
祝您编码顺利!
在Java的构造函数中使用过多的参数可能会导致代码混乱和难以维护。为了解决这个问题,可以使用Builder模式。但是,如果不正确地使用Builder模式,会引入创建不完整对象的风险。
除了使用Builder模式,还有其他改进设计的方法。例如,将名字和姓氏(以及导演的全名)作为单独的字符串传递。可以创建一个PersonName类来封装这些不同的命名元素,这样构造函数就变成了:
public Book(String title,
PersonName directorName,
String type,
int issueYear,
List
...
}
这样看起来更清晰,也使命名更一致。
当然,还应该将该类重命名为Movie而不是Book。
你只是重复了之前的答案。你可以轻松地检查到这一点,因为在你回答之前我已经标记了这个问题。请不要回答明显的重复问题。