gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:26:13 26 4
gpt4 key购买 nike

这是试图理解 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com