Disclaimer: I’m new to programming in Java and working with “extreme” OOP in general, so the answer to this might be really simple.
I’m creating a user interface in Vaadin, a Web application framework that supplies lots of useful components for me. Often, I’m not entirely happy with the default settings for these components.
For example, if I want every TextField
component to fire value change events immediately when the field loses focus. There are similar settings for UploadField
, TextArea
, ComboBox
etc. that I want to set on every instance of those classes.
Currently, what I have looks like this:
public class ConfiguredComponents {
public static TextField createConfiguredTextField(String caption) {
TextField field = new TextField(caption);
field.setImmediate(true);
field.setSomeOtherOptions();
...
return field;
}
public static UploadField createConfiguredUploadField(...) {
...
}
// etc.
}
This doesn’t feel like a class at all! It’s just a collection of static methods, which I’ve been told to avoid. Plus, I would like to place the logic for each component in a separate file. The configuration gets quite involved sometimes, and it just makes more sense that way: these are all very tiny self-contained bits of logic.
Here are the solutions I’ve considered:
Keep it simple: I could get rid of
ConfiguredComponents
, and just make one big package containing small factory classes. For example,myproject.ui.components.TextFieldFactory
knows how to create a configuredTextField
and nothing more.Pros:
- The ugly
ConfiguredComponents
class is gone. - All of the logic is in separate files.
Cons:
- There’s no single interface to the creation of my configured components; the only thing keeping them together is the fact that they’re in the same directory. Basically, I have to expose a lot of tiny classes, and there’s no single class or object managing them. (This intuitively feels like a pretty bad thing, but I don’t know if it really is.)
- There’s also no way to override or extend static methods, so “faking” UI stuff for testing gets harder.
- The ugly
The Abstract Factory pattern: I make
ConfiguredComponents
into anAbstractComponentFactory
that manages a lot of smaller factories.Pros:
- All of the logic is in separate files.
- The logic that actually configures my components is fully behind-the-scenes.
Cons:
I would need an instance of
AbstractComponentFactory
every time I want to create a component anywhere in the code for my views. This means either keeping a singleton object, which has a lot of downsides, or creating anew AbstractComponentFactory()
every time.I have to write new code in two or three places, instead of just one, if I wish to add new components to my little “library”.
Some other design pattern I don't know about: I’ve read a bit about Builder, and Facade, which feel like they might apply here, but I don’t understand them very well.
How would you approach this design decision?