Java design Pattern 4--builder mode (builder)

Source: Internet
Author: User

This article address: http://www.cnblogs.com/archimedes/p/java-builder-pattern.html, reprint please indicate source address.

Builder mode

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

Overview

When the system is ready to provide users with an internally complex object, you can use the generator pattern, which allows you to construct objects incrementally, making the creation of objects more resilient. The key to the builder pattern is to divide the creation of one containing multiple component objects into several steps and encapsulate them in an interface called a generator.

Applicability

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

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

Participants

1.BUILDER specifies an abstract interface for each part that creates a product object.

The 2.ConcreteBuilder implements the builder interface to construct and assemble individual parts of the product. Defines and clarifies the representation that it creates. Provides an interface for retrieving products.

3.Director constructs an object that uses the builder interface.

4.Product represents the complex object being constructed. ConcreteBuilder creates an internal representation of the product and defines its assembly process. Contains the classes that define the components that comprise the assembly, including the interfaces that assemble the parts into the final product.

Structure and use of builders ' patterns

The structure of the pattern consists of four roles:

• Products (product)

• Abstract Builder (builder)

• Specific generators (ConcreteBuilder)

• Conductor (director)

UML Class diagrams for schemas

Actual combat part

Example 1: Create a container that contains buttons, labels, and text box components. Different users have different requirements for containers, for example, some users want the container to contain only buttons and labels, and some users want the container to contain only buttons and text boxes. In addition, the user has different requirements for the order of components in the container, for example, some users require components to be left-to-right in the container in the order of the buttons, labels, text boxes, and some users require left-to-right sorting labels, text boxes, buttons.

Description and use of the structure of the pattern

1. Product: Panelproduct.java

import javax.swing.*;  Public class extends jpanel{   JButton button;    JLabel label;                   JTextField TextField;}

2. Abstract Builder (builder): Builer.java

  public  interface   builder{ abstract  void   Buildbutton ();  public  abstract  void   Buildlabel ();  public  abstract  void   Buildtextfield ();  public  abstract   JPanel Getpanel ();}  

3. Concrete Generator (ConcreteBuilder) _1: Concretebuilderone.java

Importjavax.swing.*; Public classConcretebuilderoneImplementsbuilder{Privatepanelproduct Panel; Concretebuilderone () {panel=Newpanelproduct (); }        Public voidBuildbutton () {Panel.button=NewJButton ("button"); }       Public voidBuildlabel () {Panel.label=NewJLabel ("label"); }       Public voidBuildtextfield () {} PublicJPanel Getpanel () {panel.add (Panel.button);           Panel.add (Panel.label); returnPanel; }}

3. Concrete Generator (ConcreteBuilder) _2: Concretebuildertwo.java

Importjavax.swing.*; Public classConcretebuildertwoImplementsbuilder{Privatepanelproduct Panel; Concretebuildertwo () {panel=Newpanelproduct (); }        Public voidBuildbutton () {Panel.button=NewJButton ("button"); }       Public voidBuildlabel () {} Public voidBuildtextfield () {Panel.textfield=NewJTextField ("TextField"); }       PublicJPanel Getpanel () {panel.add (Panel.textfield);            Panel.add (Panel.button); returnPanel; }} 

4. Conductor (director): Director.java

import javax.swing.*;  Public class director{    private  builder Builder;    Director (Builder builder) {       this. builder=Builder;    }       Public JPanel constructproduct () {       Builder.buildbutton ();       Builder.buildlabel ();       Builder.buildtextfield ();       JPanel Product=Builder.getpanel ();        return product;   

5. Application Application.java

Importjavax.swing.*; Public classapplication{ Public Static voidMain (String args[]) {Builder builder=NewConcretebuilderone (); Director Director=NewDirector (builder); JPanel Panel=director.constructproduct (); JFrame Frameone=NewJFrame ();       Frameone.add (panel); Frameone.setbounds (12,12,200,120);       Frameone.setdefaultcloseoperation (Jframe.dispose_on_close); Frameone.setvisible (true); Builder=NewConcretebuildertwo (); Director=NewDirector (builder); Panel=director.constructproduct (); JFrame Frametwo=NewJFrame ();       Frametwo.add (panel); Frametwo.setbounds (212,12,200,120);       Frametwo.setdefaultcloseoperation (Jframe.dispose_on_close); Frametwo.setvisible (true); }}

" Example 2": Building a man's class, making the construction and presentation separate

The class diagram looks like this:

Builder

 Public Interface Personbuilder {    void  buildhead ();     void buildbody ();     void buildfoot ();    Person Buildperson ();}

ConcreteBuilder

 Public classManbuilderImplementsPersonbuilder {person person;  PublicManbuilder () { person=NewMan (); } @Override Public voidBuildhead () {Person.sethead ("Build a man's head."); } @Override Public voidBuildbody () {Person.setbody ("Build a man's body."); } @Override Public voidBuildfoot () {Person.setfoot ("Build a man's foot."); } @Override PublicPerson Buildperson () {returnPerson ; }}

Director

 Public class Persondirector {    public person  Constructperson (Personbuilder pb) {        pb.buildhead ();        Pb.buildbody ();        Pb.buildfoot ();         return Pb.buildperson ();    }}

Product

 Public classPerson {PrivateString Head; PrivateString body; PrivateString Foot;  PublicString GetHead () {returnHead; }     Public voidSethead (String head) { This. Head =Head; }     PublicString GetBody () {returnbody; }     Public voidSetbody (String body) { This. BODY =body; }     PublicString Getfoot () {returnFoot; }     Public voidsetfoot (String foot) { This. Foot =Foot; }} Public classMansextendsPerson {}

Test

 Public class Test {    publicstaticvoid  main (string[] args) {        new persondirector ();         = Pd.constructperson (new  Manbuilder ());        System.out.println (Person.getbody ());        System.out.println (Person.getfoot ());        System.out.println (Person.gethead ());}    }
Benefits of Generator Mode

• The builder pattern encapsulates the construction of an object into a specific generator, and the user can get different representations of the object using different concrete generators.

• Control the construction of objects more finely and effectively. The builder breaks down the construction of the object into several steps, which makes the program more granular and effective in controlling the construction of the entire object.

• The generator mode decouples the object's construction from the creation of the object class, making the creation of objects more flexible and resilient.

• When adding a new concrete generator, you do not have to modify the code of the conductor, that is, the pattern satisfies the open-close principle.

You may also be interested in:

Java Design Pattern Series:

Java design mode 3--singleton mode (Singleton)

Java design Pattern 2--abstract Factory mode (Factory)

Java Design pattern (Factory method)

Introduction to Java Design Patterns 0--Design Patterns

Java design Pattern 4--builder mode (builder)

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.