Constructor mode of design mode (builder)

Definition of the constructor pattern

It means to separate the construction of a complex object from its representation, so that the same construction process can create different representations. This design pattern is called the builder pattern.
In layman's terms, if you want to create a human object, the attributes of each instance are different, that is, the height of the person is different. At this time, you can consider using the constructor mode.


Role Classification of Constructor Mode

  1. Specific products (things to be built)
  2. An abstract constructor, an interface that contains abstract methods for creating various sub-components of the product, and a method for returning the product.
  3. The concrete constructor implements the abstract constructor and renews its abstract methods.
  4. Commander, used to direct how to generate products.

Two classifications of the constructor pattern

There are a total of four roles in the constructor mode.If the commander and abstract constructor are omitted, there is only one concrete constructor, so it is a simple constructor mode for a long time.

Normal Constructor Mode

1.
If we want to create a human product. There are many attributes, we can choose a few to demonstrate. The product information is as follows:

public class Person {
    
    
    private String eyes; //眼睛
    private String mouth; //嘴
    private String legs; //腿
    
    // 省略get和set方法
}

2, the
abstract constructor, in this abstract class, define some methods to be used

/**
 * 抽象构造者
 */
public abstract class AbstractBuilder {
    
    

    //创建人类对象(产品)
    protected Person person = new Person();
    public abstract void buildEyes();
    public abstract void buildMouth();
    public abstract void buildLegs();

    //返回对象
    public Person getPerson(){
    
    
        return person;
    }
}

3.
Concrete constructor

/**
 * 具体构造者
 */
public class GirlPerson extends AbstractPersonBuilder {
    
    

    @Override
    public void buildEyes() {
    
    
        person.setEyes("大眼睛");
    }

    @Override
    public void buildMouth() {
    
    
        person.setMouth("小嘴巴");
    }

    @Override
    public void buildLegs() {
    
    
        person.setLegs("大长腿");
    }
}

4.
Commander

/**
 * 指挥者
 */
public class Director {
    
    
    //抽象构造者
    private AbstractPersonBuilder abstractPersonBuilder;

    public Director(AbstractPersonBuilder abstractPersonBuilder) {
    
    
        this.abstractPersonBuilder = abstractPersonBuilder;
    }
    //开始建造
    public Person instance(){
    
    
        abstractPersonBuilder.buildEyes();
        abstractPersonBuilder.buildMouth();
        abstractPersonBuilder.buildLegs();
        
        return abstractPersonBuilder.getPerson();
    }
}

5.
Test class

  public static void main(String[] args) {
    
    
        GirlPerson girlPerson = new GirlPerson();
        Director director = new Director(girlPerson);
        Person instance = director.instance();
        System.out.println(instance.toString());
        //log输出
        //Person{eyes='大眼睛', mouth='小嘴巴', legs='大长腿'}
   }

Maybe everyone hasn’t seen it yet. What are the benefits of such a complicated writing? The
Builder mode creates complex objects, and various parts of its products often face drastic changes, but they are combined together. The algorithm is relatively stable, so it is usually used in the following situations.

  • The created object is more complex and consists of multiple parts. Each part faces complicated changes, but the construction sequence among the components is stable.
  • The algorithm for creating a complex object is independent of the component parts of the object and their assembly method, that is, the product construction process and the final representation are independent.

If we now need to add a man's object again. Then we only need to create a new class inheriting the abstract constructor. The more complex the object, it will be comfortable to create with the construction model mode. The simple object is fine.


Simple constructor pattern

This construction mode is generated by removing the commander and abstract constructor.
Its function is to create an object flexibly through a constructor of the inner class.

public class User{
    
    
    String name;
    int age;
    String email;
    String address;
 
    public User(){
    
    
    }
    
    //想要有名字和邮箱的构造器
    public User(String name, String email){
    
    
        this.name = name;
        this.email = email;
    }
 
    //想要有名字和地址的构造器
    public User(String name, String address){
    
    
        this.name = name;
        this.address = address;
    }
}

In the above code, it is easy to find that under our normal needs, there will be problems with the writing of the Java constructor. Since the number of parameters and the type cannot constitute an overload, it is not possible to write this way, so the Builder mode is In order to solve this situation.

Realization of Builder mode

Let's take a look at how to write the Builder mode

public class User {
    
    
	String name;
	int age;
	String phone;
	String email;
	String address;
 
    //注意无参构造器私有,避免外界使用构造器创建User对象
	private User() {
    
    
	}
 
	@Override
	public String toString() {
    
    
		return "User [name=" + name + ", age=" + age + ", phone=" + phone + ",                 
                email=" + email + ", address=" + address
				+ "]";
	}
 
	public static class Builder {
    
    
	
		private String name;
		private int age;
		private String phone;
		private String email;
		private String address;
 
		public Builder() {
    
    
		}
		
		public Builder setName(String name) {
    
    
			this.name = name;
			return this;
		}
 
		public Builder setAge(int age) {
    
    
			this.age = age;
			return this;
		}
 
		public Builder setPhone(String phone) {
    
    
			this.phone = phone;
			return this;
		}
 
		public Builder setEmail(String email) {
    
    
			this.email = email;
			return this;
		}
 
		public Builder setAddress(String address) {
    
    
			this.address = address;
			return this;
		}
 
		public User build() {
    
    
			User user = new User();
			user.name = name;
			user.age = age;
			user.email = email;
			user.phone = phone;
			user.address = address;
			return user;
		}
	}
}

According to the above code, we can see that it is to create an internal class inside the User, and have the same fields (attributes) as the User, and provide the SET method. The most important thing is to provide a method that can return the User object (build ), so that the User object can be created through the Builder.

The Builder design pattern has another advantage, that is, we can arbitrarily combine the input parameters, which not only avoids the problem of overloading errors, but also does not need to write too many constructors.

Let's take a look at how to call after writing the Builder pattern class:

public class UserTest {
    
    
	public static void main(String[] args) {
    
    
		User u = new User.Builder().setName("bob").setAge(22).build();
		System.out.println(u);
	}	
}

Links to other design patterns

Singleton mode of
design pattern Factory mode of design pattern

Guess you like

Origin blog.csdn.net/shuai_ge_feng/article/details/104818289