Next: 2.3.2.3 Code reuse, selective
Up: 2.3.2 Illustrative Examples
Previous: 2.3.2.1 Code reuse without
2.3.2.2 Code reuse and polymorphism.
In Graphical User Interfaces, ``containers'' such as windows, frames,
panels, etc hold primitive ``components'' such as buttons, check-boxes,
text-fields, etc. In many applications, a group of such elements
exhibits similar behavior as the individual element or is controlled
similarly as the individual element. Java supports such recursive
nestings by letting java.awt.Container inherit from java.awt.Component. In fact this is an instance of the well-known composite pattern [17] that appears in various other contexts such as in
the implementation of:
- Command macros,
where a sequence of commands is treated as a command.
- Composite figures,
where a set of figures is treated as a figure.
- Nested menus, where a menu can be a menu-item.
The essence of the composite pattern is that composite elements
behave at the same time like elements and like collections
of elements. Thus they should be subtypes of both, Element and
Collection.
A composite element can ideally be defined using multiple inheritance as
follows [27]:
class CompositeElement extends Collection, Element { ... }
class CompositeElement extends Collection[Element], Element { ... }
In the latter case, Collection is a template/generic (see
Section for a discussion on generics in Java).
In Java, the composite pattern can be coded using single inheritance
of classes by:
- 1.
- defining an interface to specify the methods required of
each element (whether primitive or composite),
- 2.
- defining a class for the composite elements that
(a) implements the interface, and (b) extends an existing
collection class, and
- 3.
- requiring a client to manipulate the elements via the methods
listed in the interface.
interface Element { ... }
class BasicElement implements Element { ... }
class CompositeElement extends <SomeImplementationOfCollection>
implements Element { ... }
Next: 2.3.2.3 Code reuse, selective
Up: 2.3.2 Illustrative Examples
Previous: 2.3.2.1 Code reuse without
T. K. Prasad