Builder pattern ):
View code
Package Edu. SJTU. erplab. builder; 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; // constructor, static internal class public static class builder {// required parameter private final int servingsize; private final int servings; // optional parameter private int calories = 0; private int fat = 0; private int carbohydrate = 0; private int sodium = 0; Public Builder (INT servingsize, int servings) {This. servingsize = servingsize; this. servings = servings;} public builder calories (INT Val) {calories = val; return this; // return the builder class object itself, to link the call} public builder fat (INT Val) {fat = val; return this;} public builder carbohydrate (INT Val) {carbohydrate = val; return this ;} public builder sodium (INT Val) {sodium = val; return this;} public nutritionfacts build () {return New nutritionfacts (this) ;}} private nutritionfacts (Builder) {servingsize = builder. servingsize; servings = builder. servings; calories = builder. calories; fat = builder. fat; sodium = builder. sodium; carbohydrate = builder. carbohydrate ;}@ override Public String tostring () {// todo auto-generated method stub return "[" + "servingsize:" + servingsize + ", servings: "+ servings +", calories: "+ calories +", fat: "+ Fat +", sodium: "+ sodium +", carbohydrate: "+ carbohydrate +"] ";} public static void main (string [] ARGs) {nutritionfacts cocacola = new nutritionfacts. builder (240, 8 ). calories (100 ). sodium (35 ). carbohydrate (27 ). build (); system. out. println (cocacola );}}