简体   繁体   English

有效的Java:构建器模式

[英]Effective Java: Builder Pattern

I was reading Effective java item# 2- The Builder pattern 我正在阅读有效的Java项目#2-构建器模式

http://www.informit.com/articles/article.aspx?p=1216151&seqNum=2 http://www.informit.com/articles/article.aspx?p=1216151&seqNum=2

It is said here that java bean is not an effective way to create the object with multiple parameters. 据说Java bean不是创建具有多个参数的对象的有效方法。 But what if I have the javabean this way: 但是如果我有这种方式的javabean,该怎么办:

// JavaBeans Pattern 
public class NutritionFacts {
private final int servingSize ;
private final int servings  ;
private final int calories;
private final int fat;
private final int sodium;
private final int carbohydrate;
public NutritionFacts() { }
// Setters
public void setServingSize(int val) { servingSize = val; }
public void setServings(int val) { servings = val; }
public void setCalories(int val) { calories = val; }
public void setFat(int val) { fat = val; }
public void setSodium(int val) { sodium = val; }
public void setCarbohydrate(int val) { carbohydrate = val; }
}

Note that I made all member variables as Final 请注意,我将所有成员变量都设置为Final

Now an instance can be created this way: 现在可以通过以下方式创建实例:

NutritionFacts cocaCola = new NutritionFacts();
cocaCola.setServingSize(240);
cocaCola.setServings(8);
cocaCola.setCalories(100);
cocaCola.setSodium(35);
cocaCola.setCarbohydrate(27);

Whats wrong if I do this way? 如果这样我怎么了? Can someone help me understand? 有人可以帮我理解吗? Thanks, Rajan 谢谢,拉詹

You have not even tried to compile this, because unfortunately it will fail. 您甚至都没有尝试编译它,因为不幸的是它将失败。 The reason for this is because you declared a variable final, it must be initialized by the time the constructor is finished. 这样做的原因是因为您声明了变量final, 必须在构造函数完成时对其进行初始化。

This is incidentially why setters on final variables make no sense and also why the Builder pattern is often used to work around this problem. 顺便说一下,这就是为什么最终变量的设置器没有意义的原因,也是为什么通常使用Builder模式来解决此问题的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM