Alternative to the layout template

I read about the benefits of the builder pattern here: http://drdobbs.com/java/208403883?pgno=2

I was interested to learn about the viability of the next, which seems simpler.

public class NutritionFactParams {
    private int servingSize;
    private int servings;
    private int fat_ = 0;
    private int sodium_ = 0;
    NutritionFactParams(int servingSize, int servings) {
        this.servingSize = servingSize;
        this.servings = servings;
    }
    NutritionFactParams fat(int fat) {
        this.fat_ = fat;
        return this;
    }
    NutritionFactParams sodium(int sodium) {
        this.sodium_ = sodium;
        return this;
    }
}

public class NutritionFacts {
    public NutritionFacts(NutritionFactParams params) {
        // copy values across, or store NutritionFactParams as member
    }
}

public class Main {
    public static void main(String args[]) {
        NutritionFacts n = new NutritionFacts(new NutritionFactParams(1,2).fat(23).soduim(10));
    }
}

This is basically a builder pattern, except that the NutritionFacts constructor is open, not private, we do not have a static Builder class inside NutritionFacts, and there is no build () method in the builder. There is no alternative or standard constructor, so you cannot create NutritionFacts without first building NutritionFactsParams.

+3
source share
2 answers

The difference is small, but there is one important difference that I can think of:

, , Impl build(), , Impls (). , , Impl.

+3

, , .

, , , . .

. :


, make-builder.

+2

All Articles