Design Pattern-builder Builder pattern

Source: Internet
Author: User

Personal understanding

When the construction of the object is very complex, the parameters are many, through the constructor will produce a lot of redundant code, not good maintenance, and we do not want the caller to set the way to construct the object (encapsulation, hiding), because it is prone to problems, so that the entire construction process can be encapsulated in a construction class, A more granular construct can be constructed by constructing classes, with clear responsibilities

Intentions

Separating the construction of a complex object from its representation allows the same build process to create different representations.

Applicability

When creating complex objects, the algorithm should be independent of the parts of the object and how they are assembled.

When the construction process must allow the constructed object to have different representations.

Implementation (Java)
package com.zlf.pattern;public class buliderdemo {  private int a;  private int b;  private buliderdemo (builder builder) {  THIS.A  = builder.a;  this.b = builder.b; } public static class  Builder{  private int a;  private int b;     Public builder () {     }  public builder builda (int a) {    this.a = a;   return this;  }      public builder buildb (int b) {   this.b = b;    return this;  }     public buliderdemo create () {    return new buliderdemo (This);  }   }  public  Static void main (String[] args] {  buliderdemo test = new buliderdemo.builder (). BuildA (1). BuildB (2) . Create ();   system.err.println (test.a);  } }

?

Design Pattern-builder Builder pattern

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.