Java Reference
In-Depth Information
and lengthy class with many methods, such as setHasScrollbars(boolean b) . This solution also
does not seem like the proper object‐oriented way to program things.
Luckily, the decorator pattern can help. This pattern resembles the bridge pattern in that it con-
tains both a combination of interfaces and abstract classes. For this example, you would need the
following:
interface Window : Contains all the method signatures windows need to support, such as
setTitle(String title) .
class NormalWindow implements Window : The class implementing the bare‐bones
window.
abstract class WindowDecorator implements Window : The abstract decorator class.
Just as with the bridge pattern, this class contains an instance of a Window object, as well as
methods for all methods the Window interface defines. In the abstract calls, all method calls
are passed to the Window object (this is called delegation).
class NaggingWindowDecorator extends WindowDecorator and other decorators: These
classes define the behavior you want to add on top of another object. These classes will over-
ride all methods that need to be extended, in most cases also involving a call to the original
superclass method, which delegates to the Window object ( super.setTitle(title) ).
Once you put all of this in place, the complete code for the example above would look as follows.
Note that the code sample below makes some “quick and dirty” shortcuts to get the point across,
mainly by reusing the JFrame component in our window classes instead of writing a UI widget
library from scratch.
import javax.swing.JFrame;
public interface Window {
public void setTitle(String title);
public void addPanel(String message);
public JFrame getJFrame();
}
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class NormalWindow implements Window {
private final JFrame jFrame;
private final JPanel mainPane;
public NormalWindow() {
this.jFrame = new JFrame();
this.jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// We allow ourselves to cheat here by first setting up a scrollpane
// as the content pane for every window, with scroll bars hidden
// Decorators are then free to re-enable these
this.mainPane = new JPanel();
this.mainPane.setLayout(new BoxLayout(this.mainPane, BoxLayout.PAGE_AXIS));
JScrollPane scrollPane = new JScrollPane(mainPane,
Search WWH ::




Custom Search