Java类创建优化之Builder模式

  |   0 评论   |   0 浏览

前言

在java中,创建一个类的对象,主要是通过构造方法来实现的,但是当一个类的属性很多的时候,使用构造器就会很麻烦,而且不灵活。这个时候,Builder模式就可以上场了。

手写一个Builder模式

public class Person {
    
    private  String name;
    private  String gender;
    private float height;
    private  int age;
    private String nation;

    // 私有化构造器
    private Person(Builder builder) {
        this.name = builder.name;
        this.gender = builder.gender;
        this.height = builder.height;
        this.age = builder.age;
        this.nation = builder.nation;
    }

    /**
     * 共有静态方法,返回Builder对象
     *
     * @return
     */
    public static Person.Builder builder() {
        return new Person.Builder();
    }

    /**
     * Builder静态内部类
     */
    public static class Builder {
        private String name;
        private String gender;
        private float height;
        private int age;
        private String nation;

	// 相当于set方法
        public Builder name(String name) {
            this.name = name;
            return this;
        }

        public Builder height(float height) {
            this.height = height;
            return this;
        }

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

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

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

        public Person build() {
            // 将Builder对象传入Person构造器
            return new Person(this);
        }
    }


    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", gender='" + gender + '\'' +
                ", age=" + age +
                ", nation='" + nation + '\'' +
                '}';
    }
}

使用Builder

public class PersonTest {
    public static void main(String[] args) {
        Person tom = Person.builder()
                .name("Tom")
                .age(20)
                .gender("Male")
                .height(172.4f)
                .nation("America")
                .build();
        System.out.println(tom); // Person{name='Tom', gender='Male', age=20, nation='America'}
    }
}

使用 lombok @Builder注解

自己写一个builder太麻烦了,可以使用lombok的@Builder注解(需要先引入lombok)

@Builder
@ToString
public class Book {

    private String version;
    private String name;
    private String author;
    private float price;
    private String description;
    private String publishers;
    private int pages;
    private String isbn;

}

测试

public class Test {
    public static void main(String[] args) {
        var book = Book.builder()
                .author("Joshua Bloch")
                .version("3rd Edition")
                .name("Effective Java")
                .isbn(" 9780134685991")
                .pages(412)
                .price(54.9f)
                .publishers("Addison-Wesley Professional")
                .build();
        System.out.println(book);
    }
}

查看编译后的Book.class文件,发现与上面的写法是差不多的。

public class Book {
    private String version;
    private String name;
    private String author;
    private float price;
    private String description;
    private String publishers;
    private int pages;
    private String isbn;

    Book(String version, String name, String author, float price, String description, String publishers, int pages, String isbn) {
        this.version = version;
        this.name = name;
        this.author = author;
        this.price = price;
        this.description = description;
        this.publishers = publishers;
        this.pages = pages;
        this.isbn = isbn;
    }

    public static Book.BookBuilder builder() {
        return new Book.BookBuilder();
    }

    public String toString() {
        return "Book(version=" + this.version + ", name=" + this.name + ", author=" + this.author + ", price=" + this.price + ", description=" + this.description + ", publishers=" + this.publishers + ", pages=" + this.pages + ", isbn=" + this.isbn + ")";
    }

    public static class BookBuilder {
        private String version;
        private String name;
        private String author;
        private float price;
        private String description;
        private String publishers;
        private int pages;
        private String isbn;

        BookBuilder() {
        }

        public Book.BookBuilder version(String version) {
            this.version = version;
            return this;
        }

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

        public Book.BookBuilder author(String author) {
            this.author = author;
            return this;
        }

        public Book.BookBuilder price(float price) {
            this.price = price;
            return this;
        }

        public Book.BookBuilder description(String description) {
            this.description = description;
            return this;
        }

        public Book.BookBuilder publishers(String publishers) {
            this.publishers = publishers;
            return this;
        }

        public Book.BookBuilder pages(int pages) {
            this.pages = pages;
            return this;
        }

        public Book.BookBuilder isbn(String isbn) {
            this.isbn = isbn;
            return this;
        }

        public Book build() {
            return new Book(this.version, this.name, this.author, this.price, this.description, this.publishers, this.pages, this.isbn);
        }

        public String toString() {
            return "Book.BookBuilder(version=" + this.version + ", name=" + this.name + ", author=" + this.author + ", price=" + this.price + ", description=" + this.description + ", publishers=" + this.publishers + ", pages=" + this.pages + ", isbn=" + this.isbn + ")";
        }
    }
}

总结

使用builder来创建类对象,可以让代码更加优雅,可读性更高。


标题:Java类创建优化之Builder模式
作者:marshalby2
地址:http://www.yunxincoder.cn/articles/2020/09/08/1599569247845.html