Java/android Design Pattern Learning Note (---builder mode)

Source: Internet
Author: User
Tags gtx

In this blog we introduce the builder pattern, the builder pattern, also known as the generator pattern, is one of the creative patterns, unlike the factory approach pattern and the abstract factory pattern, which are designed to achieve polymorphism, and the builder The purpose of the pattern is to separate the construction and presentation of the object. The Builder mode is a step-by-step creation of a complex object that allows the user to control the object's construction process more finely without knowing the internal build details. A complex object has a large number of components, such as the car it has wheels, steering wheel, engine, and a variety of small parts, to assemble these parts into a car, this assembly process is undoubtedly complex, in this case, in order to achieve in the construction process to hide the details of the outside, you can use the Builder The pattern separates the parts from the assembly process, allowing the build process and components to be free to scale, while minimizing the coupling between the two.
Reprint Please specify source: http://blog.csdn.net/self_study/article/details/51707029.
PS: The technology is interested in the same shoe plus group 5,446,459,721 Exchange.

Total catalog of design patterns

Java/android design mode Learning Notes directory

features

Separating the construction of a complex object from its representation allows the same build process to create different representations. Usage Scenarios for Builder mode:

    • The same method, the different execution order, produces the different event result;
    • Multiple parts or parts can be assembled into an object, but the resulting results are different;
    • The product class is very complex, or the sequence of calls in the product class has different effects, and this time the builder model works well.
    • When initializing an object is particularly complex, such as many parameters, and many parameters have default values.
In the actual development process, the builder mode can use the Factory mode or any other creation mode to generate its own designated components, builder mode is also a good way to implement fluent interface.

UML class Diagram

The UML class diagram for the Builder mode is as follows:
  
There are four characters:

    • Product Products Module
    • Products related to the class;
    • Builder Interface or abstract class
    • Specification of the components of the product, generally the implementation of the specific component of the child class process, it should be noted that the role in the actual use of the process can be omitted, the most typical is like Alertdialog.builder, omit the Builder virtual class, will ConcreteBuilder Written as a static inner class;
    • Concreatebuilder class
    • The specific Builder class;
    • Director class
    • Unified assembly process, it is also noteworthy that in the real development process, the Director role is often omitted, and directly using a builder to assemble objects, this builder is usually a chain call, that is, the above-mentioned fluent interface, The key point is that each setter method returns itself, that is, return this, so that the setter method can be chained, the most typical is still the Alertdialog.builder class, using this method not only removes the Director role, Makes the whole structure more simple, but also can have finer control over the component process of the Product object.

Thus we can write the generic code for the Builder pattern:
Product.class

 Public classProduct { Public intPartB; Public intParta; Public int Getparta() {returnParta; } Public void Setparta(intParta) { This. Parta = Parta; } Public int GETPARTB() {returnPartB; } Public void SETPARTB(intPartB) { This. PartB = PartB; } @Override PublicStringtoString() {return "Parta:"+ Parta +"PartB:"+ PartB; }}

The Product class declares two setter methods here, followed by the Builder related classes:
Builder.class

publicabstractclass Builder {    publicabstractvoidbuildPartA(int partA);    publicabstractvoidbuildPartB(int partB);    publicabstractbuild();}

Concretebuilder.class

 Public  class concretebuilder extends Builder{    PrivateProduct Product =NewProduct ();@Override     Public void Buildparta(intParta) {Product.setparta (Parta); }@Override     Public void BUILDPARTB(intPartB) {PRODUCT.SETPARTB (PartB); }@Override     PublicProductBuild() {returnProduct }}

Builder These two classes are used to encapsulate the settings on the product property, and finally in the build method, return the Product object that finished setting the property, and finally the Director role:
Director.class

publicclass Director {    private Builder builder;    publicDirector(Builder builder) {        this.builder = builder;    }    publicvoidconstruct(intint partB) {        builder.buildPartA(partA);        builder.buildPartB(partB);    }}

Encapsulates the Builder object, and finally the test program:

Builder builder = new ConcreteBuilder();Director director = new Director(builder);director.construct(12);Product product = builder.build();Log.e("shawn", product.toString());break;

Run results

com.android.builderpattern1   2

Code at a glance, the point to mention here is that different products can be built to different concretebuilder classes, so that a concretebuilder class corresponding to a product class, which is similar to the factory method pattern, We will also introduce the difference between them in the following.

Example and source code

The Builder pattern appears and is used very often in the actual development, such as the above mentioned Alertdialog.builder, as well as the very famous third party open source framework Universal-image-loader Library Imageloaderconfig, they are all static internal Builder classes that are used.
The demo here is also implemented using the simplest internal static Builder class, only the ConcreteBuilder and the Product roles, and using chained calls to implement the above-mentioned fluent interface:
Computer.class

 Public classComputer {PrivateString CPU;PrivateString GPU;PrivateString Memorytype;Private intMemorysize;PrivateString Storagetype;Private intStoragesize;PrivateString Screentype;Private floatScreenSize;PrivateString OSType; Public Static classBuilder {//Optional parameters-initialize with default values        PrivateString CPU ="Inter-i3";PrivateString GPU ="GTX-960";PrivateString Memorytype ="DDR3 1666MHz";Private intMemorysize =8;//8GB        PrivateString Storagetype ="HDD";Private intStoragesize =1024x768;//1TB        PrivateString Screentype ="IPS";Private floatScreenSize =23.8FPrivateString OSType ="Windows Ten"; Public Builder() {        } PublicBuilderSetCPU(String CPU) { This. CPU = CPU;return  This; } PublicBuilderSetgpu(String GPU) { This. GPU = GPU;return  This; } PublicBuilderSetmemorytype(String Memorytype) { This. Memorytype = Memorytype;return  This; } PublicBuildersetmemorysize(intMemorysize) { This. memorysize = memorysize;return  This; } PublicBuilderSetstoragetype(String Storagetype) { This. Storagetype = Storagetype;return  This; } PublicBuildersetstoragesize(intStoragesize) { This. storagesize = storagesize;return  This; } PublicBuilderSetscreentype(String Screentype) { This. Screentype = Screentype;return  This; } PublicBuildersetscreensize(floatScreenSize) { This. screensize = screensize;return  This; } PublicBuilderSetostype(String OSType) { This. OSType = OSType;return  This; } PublicComputerCreate() {return NewComputer ( This); }    }Private Computer(Builder builder) {CPU = Builder.}        CPU; GPU = Builder.        GPU;        Memorytype = Builder.memorytype;        Memorysize = builder.memorysize;        Storagetype = Builder.storagetype;        Storagesize = builder.storagesize;        Screentype = Builder.screentype;        ScreenSize = builder.screensize; OSType = Builder.    OSType; }}

Computer is a product class that has a Builder's static inner class for setting related properties and testing the code:

Computer computer = new computer. Builder(). SetCPU("Inter-skylake-i7"). Setgpu("Gtx-titan"). Setmemorytype("Ddr4-2133mhz"). Setmemorysize( -). Setstoragetype("SSD"). Setstoragesize( +). Setscreentype("IPS"). Setscreensize( -). Setostype("UBUNTU/WINDOW10"). Create();

The key point to mention here is the default value problem for the related property:

    • For the necessary property values, it is best to pass in the constructor of the Builder class, such as the Context of the Alertdialog.builder class, so that it is not possible to give its default value, which can also prevent inadvertent use;
    • For non-essential properties, it is best to generate a default property value for it so that the user can only set the property that needs to be changed;
    • Each setter function is added with return this to achieve a graceful fluent interface design.

Summary

The builder mode is also very common in Android development, often as the builder of the configuration class separates the build and presentation of the configuration, and isolates the configuration from the target class, avoiding too many setter methods. The most common form of implementation of the Builder pattern is through the invocation chain, which makes the code more concise and understandable, and avoids the target class being "contaminated" by too many interfaces.
Benefits of the Builder model:

    1. Encapsulates the creation of a complex object so that the client does not have to know the details of the internal composition of the product;
    2. Allows the object to be created through multiple steps, and can change the process and select the required process;
    3. The implementation of the product can be replaced because the client sees only an abstract interface;
    4. Creators are independent and easy to expand.
Builder Mode Disadvantages:
    1. Generates redundant Builder objects and Director objects, consuming memory;
    2. Customers who create objects in the Builder mode require more domain knowledge than the factory model.

Builder Mode VS Factory method mode

Both the builder and factory method models are created patterns, and they have something in common: both design patterns encapsulate the creation of a product class object, decoupling the client from the production of a specific product class, without having to understand the details of the product class construct. But there are a lot of differences between the two design patterns:

    • The Builder mode allows the creation of objects to be created through multiple steps, and can change the process or select the properties that need to be changed; The factory method pattern is different, it has only one step, it can not change the process, more can not selectively change the properties;
    • The purpose of the builder pattern is to separate the construction of the complex object from its representation, while the factory method pattern defines an interface for creating objects, which subclasses decide which class to instantiate and defer instantiation to subclasses;
    • The most obvious of course is the difference in code, in which the client can call the set method, whereas the factory method pattern can only invoke the related methods provided by the factory class.
The second is the difference between UML class diagrams:
Builder mode UML class diagram:
  
Note: The Director class and the Builder virtual class can be streamlined.
Factory method Mode UML class diagram:
  
The similarity of UML class diagrams is still very high, so we usually distinguish between the buidler pattern and the factory method pattern according to the actual performance and use (this is similar to the difference between the decorator pattern and the protection agent pattern, which differs from the actual performance and the purpose of use).

Source Download

Https://github.com/zhaozepeng/Design-Patterns/tree/master/BuilderPattern

References

http://blog.csdn.net/jason0539/article/details/44992733
Https://en.wikipedia.org/wiki/Builder_pattern

Java/android design Mode learning Note (---builder mode

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.