builder模式

比较简单,看个例子:

package com.qs.mmeng.design.pattern.builder;

import lombok.ToString;

/**
 * tutorial
 *
 * @author qs
 * @date 2018/09/10
 */
@ToString
public class Student {

	private Integer id;

	private String no;

	private String name;

	private String sex;

	private Integer age;

	public Student() {

	}

	public Student(Student student) {
		this.id = student.id;
		this.no = student.no;
		this.name = student.name;
		this.sex = student.sex;
		this.age = student.age;
	}

	public static Builder builder() {
		return new Builder();
	}

	public static class Builder {

		private Student target;

		public Builder() {
			this.target = new Student();
		}

		public Builder id(Integer id) {
			target.id = id;
			return this;
		}

		public Builder no(String no) {
			target.no = no;
			return this;
		}

		public Builder name(String name) {
			target.name = name;
			return this;
		}

		public Builder sex(String sex) {
			target.sex = sex;
			return this;
		}

		public Builder age(Integer age) {
			target.age = age;
			return this;
		}

		public Student build() {
			return new Student(target);
		}

	}

}

测试:

    @Test
    public void builderTest() {
        Student student =
                Student.builder().id(1).no(UUID.randomUUID().toString().replaceAll("-", ""))
                        .name("Tom").sex("男").age(12).build();
        System.out.println(student);
    }

输出:
builder模式_第1张图片

你可能感兴趣的:(设计模式)