Analysis of builder mode of Android design mode

Design patterns are often used in the daily development process, but there are 23 kinds of design patterns. How to know these design patterns and apply them skillfully in the actual development process? Follow the book "Android source code design pattern analysis and practice" with me while learning and applying!

Today we are going to talk about the builder pattern (builder pattern)

definition

Separate the construction of a complex object from its representation, so that the same construction process can create different representations

Usage scenario

When initializing an object is particularly complex, for example, when there are many parameters and many parameters have default values, when the same method, different execution sequences and different event results are generated, multiple components or parts can be assembled into one object, but the operation effects are different. The product class is very complex, Or the calling sequence in the product class has different effects. At this time, the builder mode is very appropriate

Use examples

AlertDialog universal-image-loader

realization

Key points of implementation

In short, multiple attributes that need to be set through the set method are encapsulated in a configuration class. Each attribute should have a default value. The specific set method is placed in the internal class builder class of the configuration class, and each set method returns itself for chain call

Implementation mode

Let's take our image loading framework imageloder as an example to see the benefits of builder mode

Imageloader without builder mode

From the above code, we can see that whenever we need to add a setting option, we need to modify the code of imageloader, which violates the opening and closing principle, and there will be more and more code in imageloader, which is not conducive to maintenance. Let's see how to use the builder model to transform imageloader

First, put the settings of imageloader in a separate configuration class, and each set method returns this, so as to achieve the purpose of chain call

Modification of imageloader

Call form, isn't it familiar?

summary

When the built object needs a lot of configuration, the builder mode can be considered, which can avoid too many set methods, isolate the configuration process from the target class, and make the code structure clearer

The common implementation form of builder mode is through chain call, which is more concise and intuitive

Source address: https://github.com/snowdream1314/ImageLoader

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>