[design mode] Builder mode (Builder mode)

Builder Pattern uses many simple objects to build a complex object step by step. This type of design pattern is a creation pattern, which provides the best way to create objects.
A Builder class constructs the final object step by step. The Builder class is independent of other objects.


Separate a complex build from its representation, so that the same build process can create different representations.


Here we implement a function as follows

In order to make a suit of clothes, there are many kinds of clothes that can be made up, such as coats and trousers

Builder mode is to create a builder, according to different needs to create different sets of clothes.

  • Create product
    public class Clothes{
        private String Coat;
        private String Pants;

        public String getCoat() {
            return Coat;

        public void setCoat(String coat) {
            Coat = coat;

        public String getPants() {
            return Pants;

        public void setPants(String pants) {
            Pants = pants;

        public String toString() {
            return "Clothes{" +
                    "Coat='" + Coat + '\'' +
                    ", Pants='" + Pants + '\'' +
  • Create Builder abstract class
    public abstract class Builder{
        public abstract void setClothes(String Coat,String Pants);
        public abstract Clothes getClothes();
  • Create Builder entity class
    public class ClothesBuilder extends Builder{
        private Clothes mClothes = new Clothes();

        public void setClothes(String Coat, String Pants) {

        public Clothes getClothes() {
            return mClothes;
  • Create director class
    public class ClothesSuit{
        private Builder builder = new ClothesBuilder();
        public Clothes getClothes1(){
            builder.setClothes("shirt","Western-style trousers");
            return builder.getClothes();
        public Clothes getClothes2(){
            builder.setClothes("Short sleeve","shorts");
            return builder.getClothes();
  • Use
    public static void main(String... args) {
        ClothesSuit clothesSuit = new ClothesSuit();

        Clothes clothes = clothesSuit.getClothes1();


        clothes = clothesSuit.getClothes2();

  • Result
I/System.out: Clothes{Coat='shirt', Pants='Western-style trousers'}
I/System.out: Clothes{Coat='Short sleeve', Pants='shorts'}


Rookie tutorial

Posted by EddieFoyJr on Mon, 04 May 2020 09:42:25 -0700