First we look at the abstract factory pattern, which is to generate a separate object.
The builder pattern, in fact, is "to make a whole of several separate objects." 】
-
Let's look at the class diagram below:
-
We see the sections in the class diagram:
-
1, Director guidance: In fact, in the generation of a whole time to call the object, he to guide the builder class to achieve the generation and assembly of accessories;
-
2, Builder: generally interface (abstract class affect the specific implementation of the inheritance of the Class), is the definition of a concrete implementation of the class of an upper layer of abstraction, which is defined as the implementation of the concrete generation, assembly method;
-
3, ConcreteBuilder: Concrete implementation of the class, to achieve assembly and generation.
-
4. Product: A whole generated.
If you don't consider extensibility, you can actually see only the Contretebuilder class and the product class. Like addition in mathematics, Part1 + Part2 = Product, the operation to implement addition is the Contretebuilder class.
Here's an example:
Class Director { Public void Produce(Ibuilder Builder) {Builder.buildpart1 ("Part1"); Builder.buildpart2 ("Part2"); }} interface Ibuilder { Public void BuildPart1(String name1); Public void BuildPart2(String name2); PublicProductgetproduct();} Class Builder implements Ibuilder {product product; Public Builder() {Product =NewProduct (); }@Override Public void BuildPart1(String name1) {product.part1name = name1; }@Override Public void BuildPart2(String name2) {product.part2name = name2; }@Override PublicProductgetproduct() {returnProduct }} class Product {String part1name; String Part2name; Public Product(){} Public Product(String part1name, String part2name) { This. part1name = Part1name; This. part2name = Part2name; } PublicStringGetpart1name() {returnPart1name; } Public void Setpart1name(String part1name) { This. part1name = Part1name; } PublicStringGetpart2name() {returnPart2name; } Public void Setpart2name(String part2name) { This. part2name = Part2name; }@Override PublicStringtoString() {return "Product:part1name="+ Part1name +", part2name="+ Part2name; } } Public class buildertest { Public Static void Main(string[] args) {Product Product =NewProduct (); Ibuilder Builder =NewBuilder (); Director Director =NewDirector (); Director.produce (builder); Product = Builder.getproduct (); System.out.println (Product.tostring ()); }}
The assembly is achieved by directing the director to the name.
This allows the builder model to be implemented.
Try it.
Design pattern (iv)--builder mode