java build创建对象 使用构建器模式实现fluent链式编程

java build创建对象 使用构建器模式实现fluent链式编程

1.方法1使用lombok创建对象

pom引入下面依赖

>
    >org.projectlombok>
    >lombok>
    >1.16.22>
>

使用@Builder注解

package com.dume.boot.code;

import lombok.Builder;
import lombok.Data;


/**
 * @author dume
 * @create 2021-12-31 11:29
 **/
//链式编程
@Builder(toBuilder = true)
//免写getter setter方法
@Data
public class Order {
    private String id;

    private Integer age;

    private String name;


}

2.方法2手动实现build对象

代码:

package com.dume.boot.code;

/**
 * @author dume
 * @create 2022-01-29 14:07
 **/
public class PersonOrder {

    private String id;

    private Integer age;

    private String name;

    public PersonOrder(Builder builder) {
        this.id = builder.id;
        this.age = builder.age;
        this.name = builder.name;
    }

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

    @Override
    public String toString() {
        return "PersonOrder(" +
                "id=" + id  +
                ", age=" + age +
                ", name=" + name +
                ')';
    }

    public static class Builder {
        private String id;

        private Integer age;

        private String name;

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

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

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


        public PersonOrder build(){
            return new PersonOrder(this);
        }


    }
}

3.打印测试

package com.dume.boot.code;
/**
 * @author dume
 * @create 2022-01-29 13:55
 **/
public class TestOrder {

    public static void main(String[] args) {
        Order order = Order.builder().id("1").name("2").age(3).build();
        System.out.println("打印order:"+order.toString());

        PersonOrder personOrder = PersonOrder.builder().id("3").name("4").age(6).build();
        System.out.println("打印personOrder:"+personOrder.toString());


    }
}

4.测试结果

打印order:Order(id=1, age=3, name=2)
打印personOrder:PersonOrder(id=3, age=6, name=4)

你可能感兴趣的:(开发记录,java,开发语言,后端,builder)