I love interfaces in Java. When used properly, they make for code that is highly cohesive and loosely coupled. Classes that implement interfaces or declare method parameters with interfaces are easier to reuse. One of my favorite interfaces in the Google Web Toolkit is Command. Command has one method:
public void execute();
That's it. A Command can be executed. Command, like the HasValue interface in the GWT Incubator is a very simple interface. So often in programming it is these simple building blocks that give us the greatest opportunities. Let's build on Command and another basic component, Button.
public class CommandButton extends Button { public CommandButton(final String html, final Command command) { super(html); addClickListener(new ClickListener() { public void onClick(Widget sender) { command.execute(); } }); } }
There. Now we can create Buttons that execute a Command when clicked. If your application uses a lot of Buttons, that saves a lot of code for adding ClickListeners. And the code you might've put in those anonymous ClickListeners is now safely encapsulated inside a reusable Command class. I use some variation on CommandButton in almost every application I build. Here's another one I use:
public class CommandLabel extends Label { public CommandButton(final String text, final Command command) { super(html); addClickListener(new ClickListener() { public void onClick(Widget sender) { command.execute(); } }); } }
Almost identical to CommandButton, isn't it? This one just uses a text Label instead of a Button. You can do the same with an Image if you want (and I have). I even wrote one with a ToggleButton.
At some point, I'm going to find the time to start a library project with all of these simple Widget extensions.
No comments:
Post a Comment