Java 可以扩展使用生成器模式和私有构造函数的类吗?
我有一个蹩脚的测试类,名为Box和PackageBox。 Box使用生成器模式和PackageBox,它们应该扩展Box 这里有一些代码Java 可以扩展使用生成器模式和私有构造函数的类吗?,java,oop,design-patterns,Java,Oop,Design Patterns,我有一个蹩脚的测试类,名为Box和PackageBox。 Box使用生成器模式和PackageBox,它们应该扩展Box 这里有一些代码 package console.app.model; public class Box { private String name = ""; private int weight = 0; private int width = 0; private int height = 0; // Box instance for comparison on m
package console.app.model;
public class Box {
private String name = "";
private int weight = 0;
private int width = 0;
private int height = 0;
// Box instance for comparison on method equals().
private static Box comparisonBox;
public static class Builder {
private String name = "";
private int weight = 0;
private int width = 0;
private int height = 0;
public Builder(String name) {
this.name = name;
}
public Builder weight(int weight) {
this.weight = weight;
return this;
}
public Builder width(int width) {
this.width = width;
return this;
}
public Builder height(int height) {
this.height = height;
return this;
}
public Box build() {
return new Box(this);
}
}
private Box(Builder builder) {
name = builder.name;
weight = builder.weight;
width = builder.width;
height = builder.height;
}
// Setters and getters, etc.
}
如何将Box扩展到PackageBox?
谢谢,如果出现问题,请在Box类中告诉我或替换什么。将受保护的构造函数添加到Box,然后将其子类化,从PackageBox构造函数调用受保护的构造函数。但是,如果您想走这条路,您需要为PackageBox实现一个新的生成器 如果扩展是件痛苦的事,请重写它,使之变得容易。如果其他人编写了
Box
,他们可能故意试图阻止子类化。@波希米亚人,我知道,但我正在寻找一种方法来实现这一点。也许你应该问原作者这是如何做到的。一般来说,像这样的限制是有原因的。这是《有效Java》一书中的一个例子,但书中并没有说它应该防止子类化。