Java Reference
In-Depth Information
Polymorphism provides a means to create elegant versatility in
our software. It allows us to apply a consistent approach to incon-
sistent but related behaviors. We should try to find opportunities in
our software systems that lend themselves to polymorphic solutions.
We should seek them out, actively and deliberately, before we begin
to write code.
Whenever you find situations in which different types of objects perform the
same type of behavior, there is an opportunity for a polymorphic solution. The
more experience you get, the easier it will be to detect such situations. See if you
recognize the opportunity for polymorphism in the following situations:
KEY CONCEPT
Polymorphism allows us to apply a
consistent approach to inconsistent
behaviors.
Different types of vehicles move in different ways.
All business transactions for a company must be logged.
All products produced by a company must meet certain quality standards.
A hotel needs to plan their remodeling efforts for every room.
A casino wants to analyze the profit margin for their games.
A dispatcher must schedule moving vans and personnel based on the job
size.
A drawing program allows the user to draw various shapes.
The common theme in these examples is that the same basic behav-
ior applies to multiple objects, and those behaviors are accomplished
differently depending on the specific type of object. Every circle is
drawn using the same basic techniques and information, which is
different from the information needed and the steps taken to draw a
rectangle. Yet both types of shapes get drawn. Different, but similar.
Polymorphic.
The example of a drawing program is explored in more detail in the PaintBox
case study presented in Appendix J. It follows the refinement of a large program
through various stages of its development. The heart of its design is a polymorphic
approach to handling the various types of shapes that the user can draw.
Once a polymorphic situation is identified, the specifics of the design can
be addressed. In particular, should you use inheritance or interfaces as the
mechanism to define polymorphic references? The answer to that question
lies in the relationships among the different types of objects involved. If those
objects can be related naturally by inheritance, with true is-a relationships,
then polymorphism via inheritance is probably the way to go. But if the main
thing the objects have in common is their need to be processed in a particular
way, then perhaps using an interface to create the polymorphic references is
the better solution.
KEY CONCEPT
We should hone our design senses
to identify situations that lend them-
selves to polymorphic solutions.
 
Search WWH ::




Custom Search