继承使用静态内部类生成器构建的类
我有一个带有相当多成员变量的 A 类
。为了使其不可变并在构造过程中验证成员变量,我将其构造函数设为私有,并使用内部公共静态构建器类 (ClassABuilder
) 来构建它。 (Joshua Bloch 《有效的 Java》,第 2 条)。
现在我不明白的是,其他程序员如何子类Class A
来实现他们自己的特定行为。我从书中阅读了构建器模式的缺点,但没有看到子类化作为其中之一。我错过了什么吗?有没有一种优雅的方法来解决这个问题?
让构造函数受保护是我的想法之一,但它仍然会采用 public static ClassABuilder,那么如何在子类中添加新的成员变量呢?
I have a Class A
with quite a number of member variables. In order to make it immutable and validate the member variables during construction, I made its constructor private and used an inner public static builder class (ClassABuilder
) to build it. (Joshua Bloch Effective Java, Item 2).
Now what I do not understand is, how other programmers will subclass Class A
to implemet their own specific behavior. I read through the disadvantages of Builder Pattern from the book but did not see subclassing mentioned as one. Am I missing something? Is there an elegant way around this?
Making the constructor protected
was one of my thoughts, but it would still be taking the public static ClassABuilder
, so how to add new member variables in the sub class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在
ClassB
中创建一个内部公共静态ClassBBuilder
构建器,它是ClassABuilder
的子类Create an inner public static
ClassBBuilder
builder inClassB
that is a subclass ofClassABuilder
为什么
A
的构造函数使用Builder
作为参数。当用户调用Builder.create
时,构建器必须初始化A
的默认受保护构造函数,然后简单地设置A
的字段。所以 B 你可以轻松地从A
继承类B
Why constructor of
A
useBuildler
as a parameter. When user invokesBuilder.create
, builder must initialize default protected constructor ofA
, and then simply set ofA
's fields. So B you can easily inherit classB
fromA