In fact, the builder pattern is to create an inner class in the class and then the outer class constructor passes the pair image of an inner class, and then the return value in the set and get methods in the inner class is an internal class pair image, which makes it possible to implement the builder pattern well. In fact he is like StringBuilder in the append:string a= "a"; A.append ("Wo"). Append ("Shi"). Append ("Shei"). Implements the constant append string.
Examples are as follows:
Package Com.bluezhang.innerdemo5;public class Test {public static void main (string[] args) {//StringBuffer SS = new Strin Gbuffer ("abc");//Ss.append ("123"). Append ("the") Append ("xxx");//---> "abc123000xxx"//System.out.println ( Ss.tostring ()); Qq. Builder QB = new QQ. Builder ("10000", "888888"), Qb.setage ("M"), Setsex ("male"),//. Setemail ("[email protected]"); QQ QQ = new QQ (QB); SYSTEM.OUT.PRINTLN (QQ); QQ q = Qb.build (); SYSTEM.OUT.PRINTLN (q);}} Class QQ {String qqno; String Pass; String Sex;int age; String email;//Builder public static class Builder {String qqno; String Pass; String Sex;int age; String email;//requires QQ number and password must be filled, other optional public Builder (string qqno, String pass) {this.qqno = Qqno;this.pass = Pass;} Public Builder Setage (int.) {this.age = Age;return this;} Public Builder setsex (String sex) {this.sex = Sex;return this;} Public Builder Setemail (String e-mail) {this.email = Email;return this;} 2public QQ Build () {return new QQ (this);}} Public QQ (Builder b) {this.qqno = B.qqno;this.pass = B.pass;this. sex = B.sex;this.age = B.age;this.email = B.email;} @Overridepublic String toString () {return qqno + Pass + age + sex + email;}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Builder Model Builder