public class MyButton{
public MyButton(){}
public MyButton setIcon(Icon icon){return this;}
public MyButton setText(String text){return this;}
}
And used like:
MyButton testButton = new MyButton()
.setIcon(MyIcon)
.setText("MyText");
I know its not a true implementation of the builder pattern, but is there something inherently wrong with this design?
3 Answers 3
Is it the builder pattern? As Euphoric explained, no, it is not. A Builder is a separate class which has the purpose to create an instance of a different class.
Is there anything wrong with the design? That depends. Does your application allow buttons which don't have a text and/or icon? If yes, then this pattern is perfectly acceptable. If no, you might want to consider writing a ButtonBuilder
class which throws an exception (or at least an assert
) when you call buttonBuilder.build()
before setting all required properties.
-
@COMEFROM answered the question perfectly in the comments below the question. I called it a builder pattern for lack of a better name, however calling it a fluent interface would have been much more appropriate.Rulasmur– Rulasmur2015年11月30日 12:10:31 +00:00Commented Nov 30, 2015 at 12:10
The core part of Builder patter is the build part, not the fluent syntax part.
If your class is not building another class, then it shouldn't be called builder.
In your case, I would call it "fluent property setting" or something similar.
-
Well, I didn't really know what else to call it. Anyway, is anything inherently wrong with the design?Rulasmur– Rulasmur2015年11月30日 09:30:30 +00:00Commented Nov 30, 2015 at 9:30
-
@Rulasmur What design? You are just setting properties using fluent syntax. This is more stylistic choice than design choice.Euphoric– Euphoric2015年11月30日 09:40:37 +00:00Commented Nov 30, 2015 at 9:40
As mentioned by @COMEFROM this question answered the question perfectly. The style used here is called a Fluent Interface. This answer mentions a convention which is inline with standard java convention and doesn't theoretically interfere with jvm optimizations and javabean compatibility
MyButton test = new MyButton(); test.setIcon(); test.setText();
foo.withSomething(bar)
to make a clear difference between traditional setters and fluent methods but that's really the only thing I have to say about the issue.