From Patterns to Code

In each of the following problems you must

(a) Draw a class diagram showing how you would connect the given classes and apply the given patterns. In some cases you may need to add classes, interfaces, fields, operations, and associations. Mention the patterns you are using.

(b) Translate your class diagram into working Java classes. (Methods with unspecified implementations can simply print diagnostic messages.)

(c) Write a test class with a main method that tests the code in part b.

(1) A zoo contains many animals: Tigers, Monkeys, Birds, etc. All animals make a noise at feeding time. A Tiger class already exists:

class Tiger {
   public void roar() {
      System.out.println("A tiger is roaring");
   }
}

(2) A company has many employees. Employees are persons with names, birthdays, genders, blood types, and addresses. Workers perform tasks. One day a worker may have to dig a ditch, the next day the same worker may have to lift boxes. On another day the same worker may have to write code. Managers manage workers. Managers may also manage other managers.

(3) A shape is anything that implements the Drawable interface:

interface Drawable {
   void draw(Graphics g);
   void move(int xc, int yc);
   void resize(int width, int height);
}

Examples of shapes include Box, Disk, and Assembly. An assembly is any combination of boxes, disks, and sub-assemblies.

Note: Test your code using an actual graphics program. (See graphics.htm).

(4) A GPS device computes its distance from a fixed point (say the North Pole). A distance is a non-zero number (a double) combined with a unit (meters, kilometers, inches, or miles). Distances can be added. For example:

d3 = d1.add(d2);

In this case the units of d3 are the same as the units of d1. If the units of d2 are different from the units of d1, then d2 is converted into an equivalent distance in the units of d1.

Hint: Think of the unit of a distance as its type. Where would be the best place to compute conversions?

Patterns

The above exercises use the following patterns:

Actor-Role

Types as Objects

Strategy

Adapter

Composite

The last three are "Gang of Four" patterns that you can use the StarUML Apply Pattern tool to instantiate.

Implementation

Make use of generic collections for representing aggregates (such as zoos or employees).

Be sure to include necessary bookkeeping methods to all of your Java classes: constructors, getters, setters, add, remove, etc.