java - 调整 Builder 模式以进行方法调用

标签 java design-patterns methods builder effective-java

这是试图理解 Effective Java 第 2 版中的第 40 项:仔细设计方法签名的一部分。

提高方法签名可读性的建议之一是针对四个或更少的参数。建议使用多种技术来管理更长的参数列表,其中之一如下:

A third technique that combines aspects of the first two is to adapt the Builder pattern (Item 2) from object construction to method invocation. If you have a method with many parameters, especially if some of them are optional, it can be beneficial to define an object that represents all of the parameters, and to allow the client to make multiple “setter” calls on this object, each of which sets a single parameter or a small, related group. Once the desired parameters have been set, the client invokes the object’s “execute” method, which does any final validity checks on the parameters and performs the actual computation.

我熟悉 Builder 模式,因为它用于对象构造,但不确定我是否正确理解了如何使其适应方法调用。

到目前为止,这是我所拥有的:
(我试图改进move方法的方法调用)

public class Space {

    public static class Builder {
        // Required parameters
        private final int x;
        private final int y;
        private final int z;

        // optional params
        private long time = 0;

        public Builder(int x, int y, int z) {
            this.x = x;
            this.y = y;
            this.z = z;
        }

        public Builder time(long val) {
            time = val;
            return this;
        }

        public void move() {
            if (x == 0 || y == 0 || z == 0) {
                throw new IllegalArgumentException("Cannot move to the centre of the universe");
            }

            // Do the actual work here
        }
    }

//  public void move(int x, int y, int z, long time) {
//      // Do the work here
//  }

    public static void main(String[] args) {
        new Builder(1, 1, -1).time(1234).move();
    }
}

我对 Joshua Bloch 的建议的解释是否正确?

最佳答案

在我看来,您可以将构建器类与父类相关联(例如使用 non-static inner class ),并且客户可以像这样使用它:

Space space = new Space();
...
Space.MoveBuilder moveBuilder = space.new MoveBuilder(1, 1, -1);
moveBuilder.setTime(1234);
moveBuilder.execute();

它可以通过使用流畅的构建器和工厂方法进一步简化:

space.startMove(1, 1, -1).withTime(1234).endMove();

关于java - 调整 Builder 模式以进行方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13954672/

相关文章:

java - 从文件数据中提取特定段落的最佳方法

java - 使用方法在 ArrayList 中循环

java - 为什么 System.out.println 这么慢?

java - 如何在类实例和这些属性的其他可能用户之间共享属性?

oop - 用于管理对象依赖关系的设计模式

c++ - 为什么 'visitor pattern'要求每个类都继承VisitorHost接口(interface)类并具有accept()函数?

objective-c - 类别中重写的方法是否始终优先于原始实现?

java - 使用多种方法时缺少返回语句错误

java - 从 ConnectionPools 获取和释放 JDBC 连接的频率?

java - Hazelcast Ringbuffer readManyAsync 返回空结果