package builder_pattern;
import java.util.ArrayList;
public class Product {
ArrayList<String> parts = new ArrayList<String>();
public void add(String part) {
parts.add(part);
}
public void show() {
System.out.println("The parts of product are:");
for(String str:parts) {
System.out.println(str);
}
}
}
package builder_pattern;
public abstract class Builder {//The abstraction of concreted method.
//These methods' concreted content are always changed in the future.
//But the methods' name will be not changed.
public abstract void BuilderPartA();
public abstract void BuilderPartB();
public abstract Product GetResult();
}
package builder_pattern;
public class ConcreteBuilder1 extends Builder{
private Product product = new Product();
@Override
public void BuilderPartA() {//The changing part.
product.add("PartA");
}
@Override
public void BuilderPartB() {//The changing part.
product.add("PartB");
}
@Override
public Product GetResult() {
return product;
}
}
package builder_pattern;
public class ConcreteBuilder2 extends Builder{
private Product product = new Product();
@Override
public void BuilderPartA() {//The changing part.
product.add("PartX");
}
@Override
public void BuilderPartB() {//The changing part.
product.add("PartY");
}
@Override
public Product GetResult() {
return product;
}
}
package builder_pattern;
public class Director {
//The order of every concreted product's construction will be constant.
public void Construct(Builder builder) {//Not changed.
builder.BuilderPartA();
builder.BuilderPartB();
}
}
package builder_pattern;
public class Main {
public static void main(String args[]) {
Director director = new Director();
Builder b1 = new ConcreteBuilder1();
Builder b2 = new ConcreteBuilder2();
director.Construct(b1);
Product p1 = b1.GetResult();
p1.show();
director.Construct(b2);
Product p2 = b2.GetResult();
p2.show();
}
}
/* The product is the product.
* The director is responsible for the order of the whole product's
* construction,which is constant more often.
* The Builder is responsible for constructing every part of a product's
* implementation in detail,which always changed.
* The concreted builder composites the product so as to implements the
* production and definite every part's contents.
*/
This is a general introduction to the 23 design patterns:
https://blog.csdn.net/GZHarryAnonymous/article/details/81567214