Builder模式的修改,是好的做法吗?
Modification of Builder pattern, is it good practice?
我正在尝试在代码中建立强制条件。代码如下:
public class Foo {
public Type;
public int planeId;
public int carId;
public int capacity;
public String manufacturer;
public int serialId;
.. etc
}
现在 Type
是一个枚举,AIRPLANE 和 CAR 作为 2 个值。条件是如果 Type
是平面,则需要填充 planeId,否则必须填充 CarId。由于 class Foo
有很多参数,我们选择了构建器模式。
public static class Builder {
public Builder(public Type type, int id) {
if (type == PLANE) {
planeId = id;
} else {
carId = id;
}
}
但后来我有了一个想法,将静态工厂融合到构建器模式中
public static class Builder {
public static Builder getPlaneBuilder(int id) {
return new Builder(PLANETYPE, id); // calls private constructor
}
public static Builder getCarBuilder(int id) {
return new Builder(CARTYPE, id); // calls private constructor
}
我从未见过将静态工厂融合到构建器中,但它们似乎做得很好。任何意见 ?批评?更好的解决方案?
Condition is that if Type is plane, then planeId needs to be
populated, else CarId has to be populated.
如果 carId
用于 Car
对象而 planeId
用于 Plane
对象,您是否应该没有两个不同的 classes 来处理它们并且仅在需要的地方声明这些字段?
在两个 class 中添加仅在单个 class 中相关的字段可能是不可取的。它降低了 class.
字段的凝聚力
关于你的问题,使用工厂方法当然是个好主意。
当您想控制实例的创建时,它通常很有用(对于您来说,构建器已经是这种情况)。
但当您有多种构造对象的方法并且构造函数没有传达有关您要创建的内容的足够信息时,它也很有用。
例如这是一个很好的例子:
public static Builder getPlaneBuilder(int id) {
return new Builder(PLANETYPE, int id); // calls private constructor
}
来自客户端代码 getPlaneBuilder(int id)
比 public Builder(public Type type, int id)
更有意义。
我正在尝试在代码中建立强制条件。代码如下:
public class Foo {
public Type;
public int planeId;
public int carId;
public int capacity;
public String manufacturer;
public int serialId;
.. etc
}
现在 Type
是一个枚举,AIRPLANE 和 CAR 作为 2 个值。条件是如果 Type
是平面,则需要填充 planeId,否则必须填充 CarId。由于 class Foo
有很多参数,我们选择了构建器模式。
public static class Builder {
public Builder(public Type type, int id) {
if (type == PLANE) {
planeId = id;
} else {
carId = id;
}
}
但后来我有了一个想法,将静态工厂融合到构建器模式中
public static class Builder {
public static Builder getPlaneBuilder(int id) {
return new Builder(PLANETYPE, id); // calls private constructor
}
public static Builder getCarBuilder(int id) {
return new Builder(CARTYPE, id); // calls private constructor
}
我从未见过将静态工厂融合到构建器中,但它们似乎做得很好。任何意见 ?批评?更好的解决方案?
Condition is that if Type is plane, then planeId needs to be populated, else CarId has to be populated.
如果 carId
用于 Car
对象而 planeId
用于 Plane
对象,您是否应该没有两个不同的 classes 来处理它们并且仅在需要的地方声明这些字段?
在两个 class 中添加仅在单个 class 中相关的字段可能是不可取的。它降低了 class.
关于你的问题,使用工厂方法当然是个好主意。
当您想控制实例的创建时,它通常很有用(对于您来说,构建器已经是这种情况)。
但当您有多种构造对象的方法并且构造函数没有传达有关您要创建的内容的足够信息时,它也很有用。
例如这是一个很好的例子:
public static Builder getPlaneBuilder(int id) {
return new Builder(PLANETYPE, int id); // calls private constructor
}
来自客户端代码 getPlaneBuilder(int id)
比 public Builder(public Type type, int id)
更有意义。