In java.awt, the Bridge pattern is used to separate the logical description of a GUI from its description in a particular GUI component library such as Win32, GTK, XWindows, etc. This means the GUI doesn't need to be rewritten when the application is ported to a new platform. Let's imitate this trick for our framework:
But how will a GUI component know what type of peer it should use? This information won't be known until runtime. We can use the AbstractFactory pattern:
For example, here's a sketch of our Button class:
class Button extends GUIComponent { // Control is conceptual
private String text;
// draw a picture of a button:
public void paint(Graphics gc) {
gc.draw(new Rectangle(location,
size));
gc.draw(new Label(text, location));
}
public void setPeer() {
peer = kit.makeButtonPeer();
}
}
Setting the kit field determines if a Win32 button or an XWin button gets created.
Here's a sketch of the Win32PeerFactory:
class Win32PeerFactory implements AbstractPeerFactory {
public GUIComponentPeer
makeTextFieldPeer() {
W32TextFieldPeer adapter = new
W32TextFieldPeer();
adapter.adaptee = new
Win32TextField();
return adapter;
}
public GUIComponentPeer
makeButtonPeer() {
W32ButtonPeer adapter = new
W32ButtonPeer();
adapter.adaptee = new Win32Button();
return adapter;
}
// etc.
}