Builder Pattern in Java

  • 建造者模式:
    1. 建造者模式定义
    2. 建造者模式应用场景
    3. 实现案例
    4. Jdk中的建造者模式
    5. 建造者模式的优点
    6. 建造者模式的缺点

建造者模式定义

   Builder模式旨在将“复杂”对象的构造与其表示分开,以便相同的构造过程可以创建不同表示。

建造者模式应用场景

在Java编程中final类及其对象有许多好处(可以参考阅读String的实现),建造者模式可以帮助我们创建具有大量状态属性的不可变类对象。

在实际编程中,我们经常会有一些业务模块中有些对象,一旦创建其中的某些状态属性就不可变的情景,比如网约车的Trip模块(有id、owner、departure、destination、amount等属性),很多的状态一旦创建我们认为再发生变化是没有意义的;再比如我们在后端服务中构建多查询条件时,我们希望一个查询条件一旦被构建则不希望其发生变化。

正常情况下,如果我们通过构建一个普通的Java类来定义Trip,我们需要为其final属性字段定义构造函数,但是随着系统的迭代,当后期再次为Trip新增final字段时就不得不为Trip类新增一个新的参数构造器,这是及其糟糕的,这时候如果我们一开始便采用建造者模式来定义Trip则后期可以切合“相同的构造过程创建不同表示”的定义。

public Trip(String id) {...}
public Trip(String id, String owner) {...}
public Trip(String id, String owner, String departure, String destination) {...}

当然你也可以通过setter方法来设置普通类型对象,或者创建更多参数的构造函数。

实现案例

下面代码示例是我自己随机定义的,如果你的团队使用过Protocol Buffers协议来构造Java类的话,那么你应该对建造者模式非常熟悉了,Protobuf中最经典的就是建造者模式实现。

package com.iblog.pattern.builder;

public class Trip {
    private final String id;
    private final String owner;
    private final String departure;
    private final String destination;
    private final long amount;
    private final long expiredAt;
    private final String createdBy;
    private final long createdAt;
    private final String lastUpdatedBy;
    private final long lastUpdatedAt;

    private Trip(Builder builder) {
        this.id = builder.id;
        this.owner = builder.owner;
        this.departure = builder.departure;
        this.destination = builder.destination;
        this.amount = builder.amount;
        this.expiredAt = builder.expiredAt;
        this.createdBy = builder.createdBy;
        this.createdAt = builder.createdAt;
        this.lastUpdatedBy = builder.lastUpdatedBy;
        this.lastUpdatedAt = builder.lastUpdatedAt;
    }

    public Builder toBuilder() {
        return new Builder()
                .setId(this.id)
                .setOwner(this.owner)
                .setDeparture(this.departure)
                .setDestination(this.destination)
                .setAmount(this.amount)
                .setExpiredAt(this.expiredAt)
                .setCreatedBy(this.createdBy)
                .setCreatedAt(this.createdAt)
                .setLastUpdatedBy(this.lastUpdatedBy)
                .setLastUpdatedAt(this.lastUpdatedAt);
    }

    public static class Builder {
        private String id;
        private String owner;
        private String departure;
        private String destination;
        private long amount;
        private long expiredAt;
        private String createdBy;
        private long createdAt;
        private String lastUpdatedBy;
        private long lastUpdatedAt;

        /**
         * In actual combat, you can define the required fields as final types,
         * then set fields values through this constructor method.
         */
        public Builder() {}

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

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

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

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

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

        public Builder setAmount(long amount) {
            this.amount = amount;
            return this;
        }

        public Builder setExpiredAt(long expiredAt) {
            this.expiredAt = expiredAt;
            return this;
        }

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

        public Builder setCreatedAt(long createdAt) {
            this.createdAt = createdAt;
            return this;
        }

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

        public Builder setLastUpdatedAt(long lastUpdatedAt) {
            this.lastUpdatedAt = lastUpdatedAt;
            return this;
        }
    }

    public String getId() {
        return id;
    }

    public String getOwner() {
        return owner;
    }

    public String getDeparture() {
        return departure;
    }

    public String getDestination() {
        return destination;
    }

    public long getAmount() {
        return amount;
    }

    public long getExpiredAt() {
        return expiredAt;
    }

    public String getCreatedBy() {
        return createdBy;
    }

    public long getCreatedAt() {
        return createdAt;
    }

    public String getLastUpdatedBy() {
        return lastUpdatedBy;
    }

    public long getLastUpdatedAt() {
        return lastUpdatedAt;
    }

    @Override
    public String toString() {
        // you can cover this method.
        return super.toString();
    }
}

编写一个使用测试类:

package com.iblog.pattern.builder;

import org.junit.Test;

import static org.junit.Assert.*;

public class TripTest {

    @Test
    public void testTripBuilder() {
        Trip.Builder builder = new Trip.Builder();
        builder.setId("1")
                .setOwner("lance")
                .setDeparture("wuhan")
                .setDestination("shanghai");
        Trip trip = builder.build();

        assertEquals("1", trip.getId());
        assertEquals("lance", trip.getOwner());
        assertEquals("wuhan", trip.getDeparture());
        assertEquals("shanghai", trip.getDestination());
        assertEquals(0, trip.getAmount());
        assertNull(trip.getCreatedBy());
    }
}

Jdk中的建造者模式

java.lang.Appendable接口所有的实现类都是建造者模式的实例:

  1. java.lang.StringBuilder#appen()
  2. java.lang.StringBuffer#appen()
  3. java.nio.ByteBuffer#put()

建造者模式的优点

从案例中使用建造者模式之后,代码行数增加了一倍;但是建造者模式的优势在于,代码的设计更加灵活,而且美观易读;可以以高度可读的形式呈现给他人。

建造者模式可以去除多参构造函数,使得代码更容易扩展,也无需考虑构造函数中传递null值;对于及其必要属性可以在建造者类中通过构造器设置,构建不可变对象逻辑非常清晰简明;在使用建造者模式声明的Object实例化过程中,调用者可以很方便灵活地设置属性,知道调用build方法。

建造者模式的缺点

建造者模式会使得代码行数增加,甚至超过setter和getter方法的一倍,这是建造者模式最大的缺点,但是这并不能掩盖建造者模式代码高度可读的优点。

代码参考:pattern-example

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容