The builder mode is useful for situations where multiple parameters are required when constructing an object. For multiple parameters, the method name can also be used to illustrate the purpose.
But in order to construct an object, it is necessary to create its builder Builder, which can be a performance issue in some very performance-oriented situations.
Implementation Mode 1:
public class book {private final string author; // Must parameter private final string name;//must parameter private final string isbn;//must parameter private final string language; //non-mandatory parameter private final int weight;//non-mandatory parameter Private book (Builder builder) {author = builder.author; Name = builder.name;isbn = builder. Isbn;language = builder.language;weight = builder.weight;} public static class builder{private final string author;private final String name;private final string isbn;private string language;private int weight;public builder (STRING AUTHOR, STRING NAME, STRING ISBN) { THIS.AUTHOR = AUTHOR;THIS.NAME = NAME;ISBN = ISBN;} Public builder language (string&Nbsp;language) {this.language = language;return this;} Public builder weight (int weight) {this.weight = weight;return this;} Public book build () {return null;}} @Overridepublic string tostring () {return "book [author=" + author + ", name=" + name + ", isbn=" + ISBN+ ", language=" + language + ", weight=" + weight + "]";}}
How to use:
Book book = new Book.builder ("Author", "Name", "ISBN"). Language ("language"). Weight (2). build ();
Implementation Mode 2:
public class book {private final string author; // Must private final string name;//must private final string isbn;//must be private final string language; //must private final int weight;//non-mandatory private book (builder builder) {author = builder.author;name = builder.name;isbn = builder. Isbn;language = builder.language;weight = builder.weight;} Public static builder builder (STRING AUTHOR,STRING NAME,STRING ISBN) {return new builder (AUTHOR,NAME,ISBN);} Private static class builder{private final string author;private final string name;private final string isbn;private string language;private int weight;public builder (STRING AUTHOR, STRING NAME, STRING ISBN) {this.autHOR = AUTHOR;THIS.NAME = NAME;ISBN = ISBN;} Public builder language (string language) {this.language = language;return this;} Public builder weight (int weight) {this.weight = weight;return this;} Public book build () {return null;}} @Overridepublic string tostring () {return "book [author=" + author + ", name=" + name + ", isbn=" + ISBN+ ", language=" + language + ", weight=" + weight + "]";}}
How to use:
Book book = Book.builder ("Author", "Name", "ISBN"). Language ("language"). Weight (2). build ();
Implementation of Builder mode