문제

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?

도움이 되었습니까?

해결책

Create an inner public static ClassBBuilder builder in ClassB that is a subclass of ClassABuilder

다른 팁

Why constructor of A use Buildler as a parameter. When user invokes Builder.create, builder must initialize default protected constructor of A, and then simply set of A's fields. So B you can easily inherit class B from A

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top