The builder pattern is defined in design mode as a pattern for building complex objects that often require multiple-step initialization or assignment to complete. So, in the actual development process, where do we fit the builder model? It is a good practice to use builder mode instead of multi-parameter constructors.
We often face the writing of such an implementation class (assuming that the class is called dodocontact), which has multiple constructors,
Dodocontact (String name);
Dodocontact (String name, int age);
Dodocontact (string name, int age, string address);
Dodocontact (string name, int age, string address, int cardID);
The main purpose of such a series of constructors is to provide more customer invocation options to handle different construction requests. This approach is common and effective, but it has many drawbacks. The author of the class has to write a constructor for various combinations of parameters, and it also needs to set the default parameter values, which is an attentive and tedious task. Second, the flexibility of such a constructor is not high, and you have to provide some meaningless parameter values at the time of invocation, for example, Dodocontact ("Ace",-1, "SH"), obviously the age of negative is meaningless, but you do not do so, to conform to Java specifications. If such code is released, the maintainer behind it will have a headache because he doesn't know what the 1 means. For such cases, it is very well suited to use the builder mode. The key point of the builder mode is to complete the object construction process through an agent. This is the agent's responsibility to complete the steps of the build, and it is also easy to expand. Here's a piece of code that's rewritten from effective Java:
Public classDodocontact {Private Final intAge ; Private Final intSafeid; Private FinalString name; Private FinalString address; Public intGetage () {returnAge ; } Public intGetsafeid () {returnSafeid; } PublicString GetName () {returnname; } PublicString getaddress () {returnaddress; } Public Static classBuilder {Private intAge = 0; Private intSafeid = 0; PrivateString name =NULL; PrivateString address =NULL;
//Steps to build PublicBuilder (String name) { This. Name =name; } PublicBuilder Age (intval) { Age=Val; return This; } PublicBuilder Safeid (intval) {Safeid=Val; return This; } PublicBuilder Address (String val) {address=Val; return This; } PublicDodocontact Build () {//build, return a new object return NewDodocontact ( This); } } PrivateDodocontact (Builder b) { age=B.age; Safeid=B.safeid; Name=B.name; Address=b.address; }}
Finally, the client program can be very flexible to build this object.
New Dodocontact.builder ("Ace"). Age (+). Address ("Beijing"). Build (); System.out.println ("name=" + ddc.getname () + "age =" + ddc.getage () + "address" + ddc.getaddress ());
Application of builder Mode in Java (GO)