HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
 

The process of designing reusable object-oriented software is one of the hardest problems faced by object-oriented software designers. This is mainly due to the fact that different software architectures have different requirements. However, design patterns give the software designer the ability to reuse some successful designs that have been used in other projects and have proved to be successful. Thus, design patterns help software designers design successful new software by using prior successful designs as a basis for their new design.

Design Patterns are one of the most significant areas of emergence in object-oriented technology. Object-oriented software designers do not invent design patterns, but rather they discover them through experience. The usefulness of a design pattern won't be seen until it has been used and proven to be successful.

Because there are many design patterns out there, the authors of the Design Patterns[1] book classify patterns by two criteria, purpose and scope. The purpose criteria reflect what a pattern does. The scope criteria specify whether the pattern applies to classes or objects. Furthermore, the authors of the Design Patterns book organized three purposes for patterns: Creational, Structural or Behavioral. Creational patterns are concerned with the process of object creation. Structural patterns are concerned with the composition of classes or objects. Behavioral patterns specify the ways in which classes and objects interact and assign responsibilities.

Java Features
When using design patterns, solutions are expressed in objects and interfaces. Interfaces, Abstract Classes and Inheritance play a major role in implementing design patterns. The following is a review of these terms in Java.

Interfaces
An interface in Java consists of a series of declarations that are subject to two restrictions:

  1. Method declarations (if any) must not include implementation code.
  2. Variable declarations (if any) can have only constant initializers; that is variables declared static final.
For example, in the following interface:

interface Point {
void move(int x, int y);
}

Point is the name of the interface and move is a method declared inside the Point interface. Note that every interface is implicitly abstract, so the use of the abstract modifier is obsolete. Also, note that every field declaration in the body of an interface is implicitly public, static and final. Thus, it is redundant to specify any of these modifiers for such fields.

An interface in Java is used to identify a common set of methods and constants for the group of classes that implement the interface.

The interface(s) implemented by a class are identified in the "implements" clause of the class declaration. For example, the following class implements the Point interface declared above:

class Test implements Point {
void move(int x, int y) {
// implementation code goes here
}
}

Abstract Classes
An abstract class is a class that defines common behavior and has no direct instances; however, its descendant classes (known as concrete classes) have direct instances. Abstract classes may have abstract methods; that is, methods that are declared but not yet implemented. Thus, a class has abstract methods if any of the following conditions are valid:

  1. It explicitly contains a declaration of an abstract method.
  2. It inherits an abstract method from its direct superclass.
  3. A direct superinterface of the class declares or inherits a method and that class does not contain a method that implements it.
Abstract classes should not be mixed with final classes in Java. A class is declared final if no subclasses are desired or required. Also note that if a class is declared final it cannot be declared abstract as well; otherwise, a compile-time error occurs.

As an example of an abstract class consider the following Employee class:

abstract class Employee {
abstract double compute_pay();
}

The abstract class Employee declares an abstract method, compute_pay. This concrete method defines only the form of the method without implementation; thus, each subclass must provide its own implementation.

NOTE: The abstract base class, Employee, could be coded as an interface. Using an interface instead of an abstract class might look cleaner since you don't have all those abstract keywords lying around.

Inheritance
In object-oriented languages, objects are defined in terms of classes, and classes can be defined in terms of other classes. For example, cars, trucks, buses and sport cars are all examples of vehicles. Classes can be organized into a hierarchy. A subclass inherits attributes from a superclass at a higher level in the tree. These attributes include state and behavior. Subclasses can add more variables and methods to the ones they inherit from the superclass; they can also override inherited methods by providing specialized implementations for those methods.

Classes in Java can have only one superclass. That is, Java has support for single inheritance but not multiple inheritance; however, note that a class may implement multiple interfaces.

As an example, Employees can be categorized in more than one class: consultants (hourly rate) and permanent employees (salary rate) for example. Thus, we can inherit from the Employee abstract class above as shown in Listing 1.

Figure 1 shows a class diagram representing this inheritance relationship.

Figure 1
Figure 1:

Note about the figures: The figures were drawn with the Booch method's notation in mind. If a class has a small triangle with an "A" inside it, this means that the corresponding class is an Abstract Class.

Patterns
The following sections describe a case study using Java features (Interfaces, Abstract Classes, Inheritance, etc.) and object-oriented techniques (Design Patterns) to build extensible software.

The case study that we will consider is a graphics editor. The editor permits recursive groups of shapes to be constructed from circles, rectangles and triangles. Shapes that are not part of a group are root items and are available for manipulation. Constructing increasingly complex elements (groups of shapes) out of simple ones (shapes) is a technique called recursive composition. Note that we will not exploit all the patterns in this example. You may want to do that yourself as an exercise.

Factories
A Factory is an example of Creational Patterns. These patterns provide different ways to remove explicit references to concrete classes for code that needs to instantiate them. A class creational pattern class inheritance varies the class that is instantiated, while an object creational pattern delegates instantiation to another object. This is explained below through an example.

The shapes that our graphics editor will be capable of manipulating include circles, rectangles and triangles. Note that there is a common behavior with these shapes - all of them can be drawn, moved across the screen and erased. Thus, we can define Shape as an abstract class for all graphic elements that can appear in the graphics editor window. Its subclasses define primitive graphical elements such as circles, triangles and rectangles. Figure 2 depicts a representative part of the Shapes class hierarchy. The definition of the abstract Shape class looks like Listing 2.

Figure 2
Figure 2:

NOTE: Shape can be an interface instead of an abstract class.

Note that the abstract class, Shape, cannot be instantiated. Thus, an attempt like

Shape shape = new Shape();

results in a compile-time error because abstract classes are not instantiable.

Abstract Factory
The abstract class, Shape, declared in Listing 2, is an example of the Abstract Factory Pattern. It declares an interface for creating each basic kind of shape (circle, rectangle, triangle). The participants in this pattern are Shape, which is the Abstract Factory, and Circle, Rectangle and Triangle where these classes implement operations to create concrete objects. These are known as Concrete Factories.

Shape is an abstract class that declares operations common to the graphic elements that our editor will manipulate. Thus, we can extend the Shape class for each graphic element and provide our own implementation. A sample implementation of the Circle class is shown in Listing 3.

The same thing goes for the Triangle and Rectangle shapes and is shown in Listing 4.

Factory Method
Another pattern along the lines of Abstract Factory is the Factory Method Pattern. This pattern encapsulates the knowledge of which shapes to create. For instance, when the user of the graphics editor clicks on the "Draw" pull-down menu, the event will determine which shape the user has selected. Then, the Factory Method Pattern is the one responsible for what kind of shape to produce depending on the number of arguments supplied as parameters to the Factory Method. Based on this definition, we can define a Factory Method Pattern that is capable of generating different shapes depending on the number (and type) of arguments supplied. A sample implementation of a Factory Method is shown in Listing 5.

The class DrawShapeFactory is an example of a Factory Method pattern. This factory generates shapes of different types depending on the number of arguments supplied. Note that the Factory Method pattern can also be implemented differently by having an abstract class, creator of shapes, and a concrete class for creating each shape. Figure 3 shows the structure of the Factory Method pattern.

Figure 3
Figure 3:

An example of how to use the Factory of shapes is as follows:

Suppose we number the shapes: circle = 1, triangle = 2 and rectangle = 3.

Now, in the method where we handle mouse events we can check whether the Shape Number is 1, 2 or 3 and based on that we can generate different shapes. The code snippet in Listing 6 shows an example of use.

The design patterns mentioned above are not all the design patterns that can be found in a graphics editor application. You may want to check the Design Patterns book, which lists 23 design patterns, and try to exploit more patterns from the above case study. Applicable patterns include the command pattern, builder pattern, composite pattern, iterator pattern and observer pattern.

Other Design Patterns
The Adapter Pattern
The Adapter pattern is an example of structural patterns which are concerned with how classes and objects are composed to form larger structures. The Adapter pattern converts the interface of a class into another interface clients expect. For instance, if we were to add another feature, such as drawing text, to the graphics editor, then because of incompatibility we would create a new subclass of Shape and call it TextShape, for instance, and then we can implement our drawing text feature. Since we would be using an existing class, Shape, but the interface does not include text, then we would need an Adapter, in this case TextShape.

The Adapter pattern, plus some other patterns such as Visitor and Iterator, can be implemented using a new class of Java APIs from JavaSoft known as Inner Classes. Inner classes (or nested classes) are part of JDK1.1.

As a side point, note that people in the object-oriented programming community seem to have different views on inner classes. I believe that inner classes are contrary to good object-oriented design for the following reasons:

  1. The inner class has access to the implementation of the outer class and thus information hiding is violated.
  2. The inner class is dependent on the outer class. Thus, the inner class is not reusable.
The Iterator Pattern
The Iterator pattern is an example of behavioral patterns which are concerned with algorithms and the assignment of responsibilities between objects. The Iterator pattern, also known as Cursor, provides a way to access the elements of an aggregate object (e.g., array or a list) sequentially without exposing its internal structure.

For example, the "for" statement is normally used in conventional programming as the preferred means for structuring iteration over arrays. The following code snippet shows an example where we visit each element of array[i] to find the sum of the elements of the array:

for (int i = 0; i sum += array[i];
}

In this example, the aggregate array[] is processed element by element. The "for" statement specifies a specific order of visitation which is controlled by the index, i, that is visibly modified. The Iterator pattern can help in capturing the next element in the array with a next() member function, for example. Thus, the code for summing an array would look like

for (int i = 0; i <= array.length; ++i) {
sum += array.next();
}

Note how the index, i, is decoupled from visitation. Since i is not required for array indexing within the loop, it is unlikely that i gets modified accidently within the "for" loop. A more concrete example in Java is the Vector class in the package java.util package. Elements in a Vector object can be accessed using the nextElement() method of java.util.Enumeration. An analogous example to the above would be

for (Enumeration e = vector.elements(); e.hasMoreElements();) {
sum += ((Integer) e.nextElement()).intValue();
}

Successive calls to the nextElement() method return successive elements of the aggregate. An object that implements the Enumeration interface generates a series of elements, one at a time. Thus, depending on the task to be performed, an easy way to implement an Iterator pattern is to implement the Enumeration interface which provides methods to iterate through the elements of a vector, the keys of (and the values in) a hashtable.

The Observer Pattern
The Observer pattern is an example of Behavioral Patterns. It is a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. In the Observer pattern, there are subjects (or observables) that maintain some kind of state and observers that use the state represented by subjects. When a subject's state is changed, it informs one or more observers.

A variant of the Observer design pattern is supported by the Observer class in the java.util package. Each instance of this class maintains a set of observers that are notified whenever the Observable object changes in some significant way. An observer can be an object that implements interface Observer which is declared as

public interface Observer {
public void update(Observable o, Object arg);
}

The Observable class provides many useful methods, some of which include methods for adding and deleting observers, counting and notifying observers. The class is quite handy and easy to use.

Conclusion
One of the most significant areas of emergence in object-oriented technology is Design Patterns. Design Patterns represent solutions to problems that arise when developing software within a particular context. They facilitate reuse of prior successful software designs and improve key software quality factors, such as reuse, extensibility and performance. The material presented should give you a good introduction to design patterns and a start at implementing those design patterns in Java.

References:

  1. Gamma, E., Helm, R., Johnson, R., and Vlissides J., "Design Patterns: Elements of Object-Oriented Architecture", Addison-Wesley, Reading, MA, 1995.
  2. Rumbaugh, J., Blaha, M., Premerlani, W., Eddy, F., Lorensen, W., "Object-Oriented Modeling and Design", Prentice Hall, Englewood Cliffs, NJ, 1991.
  3. Booch, G., "Object-Oriented Analysis and Design with Applications", 2nd edition. Benjamin/Cummings Publishing Inc., 1995.
About the Author
Qusay H. Mahmoud is a graduate student in Computer Science at the University of New Brunswick, Saint John, Canada. This term he is teaching a course on Multimedia and the Information Highway at the university. As part of his thesis, he developed a Web-based distributedcomputing system using Java.

	

Listing 1: Inheriting from the Employee abstract class.

class Hourly_Employee extends Employee {
    double compute_pay() {
      	// implementation code goes here
    }
}

class Salaried_Employee extends Employee {
    double compute_pay() {
   	// implementation code goes here
    }
}

Listing 2. Definition of the abstract Shape class.

abstract class Shape {
  abstract public void draw(Graphics g);
  abstract public void move(int offsetX, int offsetY);
  abstract public void erase(); // paint with the background color
  abstract public boolean pick(int offsetX, int offsetY);
}

Listing 3: Simple implementation of the Circle class.

class Circle extends Shape {
    public int X, Y, Radius;

    public Circle(int x, int y, int r) { // constructor
       X = x;
       Y = y;
       Radius = r;
  }

    public void draw(Graphics g) {
        g.drawOval(X-Radius; Y-Radius; 2*Radius; 2*Radius);
  }

    public void move(int oldx, int oldy) {
       X = X+oldx;
       Y = Y+oldy;
  }

    public void erase() {
       // repaint the region with the background color
  }

    public boolean pick(int x, int y) {
       // mouse pointer is inside or on the border
       return X<=x && x<=X+Radius && Y<=y && y<=Y+Radius;
  }
}

Listing 4: Simple implementation of Triangle and Rectangle Classes.s

class Triangle extends Shape {
    // provide implementation for the different Shape's methods here
}
   
class Rectangle extends Shape {
    // provide implementation for the different Shape's methods here
}

Listing 5: Simple implementation of a Factory Method.

class DrawShapeFactory {
    private Shape shape;

    public DrawShapeFactory(int x, int y, int r) {
       shape = new Circle(x, y, r);
  }
    
    public DrawShapeFactory(int x, int y, int w, int h) {
       shape = new Rectangle(x, y, w, h);
  }

    public DrawShapeFactory(int x, int y) {
       shape = new Triangle(x, y);
  }

    public void draw(Graphics g) {
       shape.draw(g);
  }

    public void move(int x, int y) {
       shape.move(x, y);
  }
    
    public void erase() {
       shape.erase();
  }

    public void pick(int x, int y) {
       return shape.pick(x, y);
  }
}

Listing 6: Checking Shape Number in order to generate different shapes.

// save all the shapes in a vector, so we can refer back to them later!
  Vector shapes = new Vector(100);

// handle mouse events
  public boolean mouseDown(Event e, int x, int y) {
      last_x = x;
      last_y = y;

      if (ShapeNum == 1) { // Circle
         DrawShapeFactory g;
         g = new DrawShapeFactory(last_x, last_y, 70);
          // draw the circle in different colors
          // ...
          // call other methods such as painting the screen...etc
          //
          shapes.addElement(new Circle(last_x, last_y, 70);
    }
      else if (ShapeNum == 2) { // Triangle
         // call DrawShapeFactory with different arguments.
        // ...
          shapes.addElement(new Triangle(last_x, last_y);
    }
      else { // Rectangle
         // call DrawShapeFactory with different arguments.
       // ...
         shapes.addElement(new Rectangle(last_x, last_y, 90, 120);
    }
  }


 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.