Problem leads to:
Android developer have written Alertdialog, using a new builder first, then set the value of the property in the builder, and finally call build to get the class instance and complete the instantiation of the abstract class.
Why is instantiation of a class not a simple new object, and why use this builder mode to build?
Hard-to-write, hard-to-read, hard-to-maintain overlapping constructors:
dialog need to set the necessary parameters Ignorebutton, Positivebutton, and optional title, content, icon parameters, so there is more than one constructor, similar to
New Dialog (Ignorebutton, Positivebutton);
New Dialog (title, Ignorebutton, Positivebutton);
....
Code often has a class with more than one constructor, the number of parameters of the constructor is generally incremented, layer calls, we call him overlapping constructor pattern (telescoping constructor).
The number of parameters to use this will not be a problem, the number of arguments, when creating a constructor, write parameters can be a headache, modify parameters can be difficult to maintain.
Easy to maintain, inconsistent JavaBean:
Using JavaBean, you can avoid the problem of not knowing which field to correspond to and modifying the parameter type. The corresponding fields and types are defined in the setter method of the JavaBean. The overlapping construction method is omitted.
But JavaBean also has his flaws, JavaBean objects can be called setter method at any time to set, which will make the bean lack of consistency, that is, the consistency of the class instance is not guaranteed. Especially in the case of multithreading, there will be difficult to analyze the bug.
1classbean{
2intX
3intY
4Setx () {}
5Sety () {}
6}
Builder objects that ensure consistency and flexibility:
The builder mode solves the problem of JavaBean consistency by creating an internal builder class in the bean and setting the corresponding property to builder using a setter-like method in the builder. The Bean object is then instantiated through the public bean Build () {} method and returned to the client caller, it is important that the bean object is deterministic, and the builder mode is flexible and can generate multiple custom Bean objects from different setters.
classbean{
classbuilder{
intX
intY
PublicvoidSetX (intx) {
This. x = x;
}
PublicvoidSety (intY) {
This. y = y;
}
PublicBean Build () {
returnNewBuilder ();
}
}
}
How customers use the Builder mode:
Bean Bean = (NewBean.builder ()). SetX (8). Sety (9). build ();Bean Bean2 = (NewBean.builder ()). SetX (1). Sety (2). build ();
Beans and Bean2 are 2 completely separate objects, and each individual object is created without a change in the thread safety caused by the problem.
Mode in Android: The benefits of builder mode appreciation