[Design pattern] an implementation of the builder Mode

Source: Internet
Author: User

Application scenarios

To create different types of objects based on different parameters, it is common to define multiple constructors for calling in different scenarios. But there is a better constructor method that we can implement using the builder mode (only if there are multiple constructor parameters ).
Example (automobile class and its builder)
Public class car {private final int seet; private final string engine; private final int Dormer; private final int speed; private final int color; public static class builder {private int seet; private string engine; // optional parameters private int Dormer; private int speed; private int color; Public Builder (INT Seet, string engine) {This. seet = seet; this. engine = engine;} public builder Dormer (INT Val) {This. dormer = val; return this;} public builder speed (INT Val) {This. speed = val; return this;} public builder color (INT Val) {This. color = val; return this;} public car build () {return new car (this) ;}}; private car (Builder) {This. seet = builder. seet; this. engine = builder. engine; this. dormer = builder. dormer; this. speed = builder. speed; this. color = builder. color ;}}

Demonstration of Automobile Manufacturing Process(Different cars need different parts ):

 
Public class main {public static void main (string [] ARGs) {car car1 = new car. builder (4, "power "). dormer (1 ). speed (1, 1000 ). color (0, 255 ). build (); car car2 = new car. builder (2, "awesome "). speed (1, 2000 ). color (0, 122 ). build ();}}
Isn't it cool to build freely in combination?
Extension To achieve better scalability, the builder class can be independent and inherit from a builder interface. In addition, as shown in the preceding example, builder re-defines the attributes of the car class, which consumes a certain amount of performance. Therefore, when there are few optional parameters, this builder mode is not recommended.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.