Effective Java 英文 第二版 读书笔记 Item 2:Consider a builder when faced with many constructor parameters.

package builderManyPara;

//JavaBeans Pattern - allows inconsistency,mandates mutability
public class NutritionFactsBean {
    // Parameters initialized to default values(if any)
    // required
    private int servingSize = -1;
    private int servings = -1;

    // option
    private int calories = 0;
    private int fat = 0;
    private int sodium = 0;
    private int carbohydrate = 0;

    public NutritionFactsBean(int servingSize, int servings) {
        super();
        this.servingSize = servingSize;
        this.servings = servings;
    }

    public int getServingSize() {
        return servingSize;
    }

    public void setServingSize(int servingSize) {
        this.servingSize = servingSize;
    }

    public int getServings() {
        return servings;
    }

    public void setServings(int servings) {
        this.servings = servings;
    }

    public int getCalories() {
        return calories;
    }

    public void setCalories(int calories) {
        this.calories = calories;
    }

    public int getFat() {
        return fat;
    }

    public void setFat(int fat) {
        this.fat = fat;
    }

    public int getSodium() {
        return sodium;
    }

    public void setSodium(int sodium) {
        this.sodium = sodium;
    }

    public int getCarbohydrate() {
        return carbohydrate;
    }

    public void setCarbohydrate(int carbohydrate) {
        this.carbohydrate = carbohydrate;
    }

    public static void main(String[] args) {
        NutritionFactsBean nutritionFactsBean=new NutritionFactsBean(240, 8);
        nutritionFactsBean.setFat(8);
    }
}

A JavaBean may be in an inconsistent state partway through its construction.

The JavaBean pattern precludes the possibility of making a class immutable.

package builderManyPara;

//Builder Pattern
public class NutritionFactsBuilder {

    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 static class Builder implements Builders<NutritionFactsBuilder> {
        // Required parameters
        private final int servingSize;
        private final int servings;

        // Optional parameters - initialized to default values
        private int calories = 0;
        private int fat = 0;
        private int sodium = 0;
        private int carbohydrate = 0;

        public Builder(int servingSize, int servings) {
            super();
            this.servingSize = servingSize;
            this.servings = servings;
        }

        public Builder calories(int calories) {
            this.calories = calories;
            return this;
        }

        public Builder fat(int fat) {
            this.fat = fat;
            return this;
        }

        public Builder sodium(int sodium) {
            this.sodium = sodium;
            return this;
        }

        public Builder carbohydrate(int carbohydrate) {
            this.carbohydrate = carbohydrate;
            return this;
        }

        public NutritionFactsBuilder build() {
            return new NutritionFactsBuilder(this);
        }

    }

    private NutritionFactsBuilder(Builder builder) {
        servingSize = builder.servingSize;
        servings = builder.servings;
        calories = builder.calories;
        fat = builder.fat;
        sodium = builder.sodium;
        carbohydrate = builder.carbohydrate;
    }

    public static void main(String[] args) {
        NutritionFactsBuilder nutritionFacts = new NutritionFactsBuilder.Builder(240, 8)
                .calories(100).sodium(35).build();
    }
}
package builderManyPara;

//A builder for objects of type
public interface Builders<T> {
    public T build();
}

In summary,the Builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters,especially if most of those parameters are optional.Client code is much easier to read and write with builders than with the traditional telescoping constructor pattern,and builders are much safer than JavaBeans.

时间: 2024-08-01 10:44:30

Effective Java 英文 第二版 读书笔记 Item 2:Consider a builder when faced with many constructor parameters.的相关文章

Effective Java 英文 第二版 读书笔记 Item 3:Enforce the singleton property with a private constructor or an enum type.

Making a class a singleton can make it difficult to test clients. package singletonProperty; //ingleton with public final field public class ElvisField { public static final ElvisField INSTANCE=new ElvisField(); private ElvisField(){ } } package sing

Effective Java 英文 第二版 读书笔记 Item 7:Avoid finalizers

Finalizers are unpredictable,often dangerous,and generally unnecessary. Their use can cause erratic behavior,poor performance,and portability problems. Finalizers have a few valid uses,which we’ll cover later in this item,but as a rule of thumb,you s

Effective Java 英文 第二版 读书笔记 Item 5:Avoid creating unnecessary objects.

It is often appropriate to reuse a single object instead of creating a new functionally equivalent object each time it is needed.Reuse can be both faster and more stylish.An object can always be reused if it is immutable. String s=new String(“no”); 

Effective Java 英文 第二版 读书笔记 Item 11:Override clone judiciously

x.clone()!=x will be true x.clone().getClass()==x.getClass() will be true x.clone().equals(x) always true. 意味着深复制,新建对象,数据与结构与原对象一致, Copying an object will typically entail creating a new instance of tis class,but it may require copying of internal da

Effective Java 英文 第二版 读书笔记 Item 10:Always override toString

for example,[email protected]  class [email protected]+unsigned hexadecimal representation of hashcode. define: a concise but informative representation that is easy for a person to read providing a good toString implementation makes your class much

Effective Java 英文 第二版 读书笔记 Item 4:Attempting to enforce noninstantiability by making a class abstract does not work.

The class can be subclassed and the subclass instantiated.Futhermore,it misleads the user into thinking the class was designed for inheritance(继承). There is,however,a simple idiom to ensure noninstantiability.A default constructor is generated only i

Effective Java 英文 第二版 读书笔记 Item 13:Minimize the accessibility of classes and members

访问修饰符的可见域 • private—The member is accessible only from the top-level class where it is declared.• package-private—The member is accessible from any class in the packagewhere it is declared. Technically known as default access, this is the access leve

实习第16天 开新坑 Effective Java 英文 第二版 读书笔记

最近每天上班下班有点时间看下 Effective Java. 我一般看看原文,在看看示例代码,再想想原文的意思. 我英文也不是很好,所以决定中文英文随便用. Creating and destroying objects Item 1: Consider static factory methods instead of constructors Advantage of static factory methods 1.Unlike constructors. They have names.

《Effective Java中文版第二版》读书笔记

说明 这里是阅读<Effective Java中文版第二版>的读书笔记,这里会记录一些个人感觉稍微有些重要的内容,方便以后查阅,可能会因为个人实力原因导致理解有误,若有发现欢迎指出.一些个人还不理解的会用斜线标注. 第一章是引言,所以跳过. 第二章 创建和销毁对象 第1条:考虑用静态工厂方法代替构造器 含义 静态工厂方法是指一个返回类的实例的静态方法,例如: public static Boolean valueOf(boolean b) { return b ? Boolean.TRUE :