Builder design pattern is well explained in the Effective Java book. When we have many parameters for constructors, then we can use Builder for same.Below is a code example for same.
package com.developerasks.design.builder;
public class Medicines {
private final String name;
private final String Usage;
private final float energy;
private final float protein;
private final float Carbs;
private final float sugar;
private final float fat;
private final float Iron;
private final float FolicAcid;
public static class Builder{
private final String name;
private final String Usage;
private float energy =0;
private float protein=0;
private float Carbs=0;
private float sugar=0;
private float fat=0;
private float Iron=0;
private float FolicAcid =0;
public Builder(String name, String Usage) {
this.name = name;
this.Usage = Usage;
}
public Builder energy(float val) {
energy = val;
return this;
}
public Builder protein(float val) {
protein = val;
return this;
}
public Builder Carbs(float val) {
Carbs = val;
return this;
}
public Builder sugar(float val) {
sugar = val;
return this;
}
public Builder fat(float val) {
fat = val;
return this;
}
public Builder Iron(float val) {
Iron = val;
return this;
}
public Builder FolicAcid ( float val) {
FolicAcid = val;
return this;
}
public Medicines build() {
return new Medicines(this);
}
}
private Medicines(Builder builder) {
// TODO Auto-generated constructor stub
name= builder.name;
Usage= builder.Usage;
energy =builder.energy;
protein=builder.protein;
Carbs=builder.Carbs;
sugar=builder.sugar;
fat=builder.fat;
Iron=builder.Iron;
FolicAcid = builder.FolicAcid;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return this.name+this.Usage+this.energy+this.Carbs+this.sugar+this.fat+this.Iron+this.FolicAcid;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Medicines fertile = new Medicines.Builder("FertileF", "Once Daily").energy(6).Carbs(78).fat(1).FolicAcid(3).build();
System.out.println(fertile);
}
}
ConversionConversion EmoticonEmoticon