Simple Patterns Lab

This lab uses the following patterns:

Strategy, Decorator
Composite, Visitor
Publisher-Subscriber
Adapter, Bridge

Seeing Patterns

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.

(a) Patterns: Composite, Strategy
Classes: Worker, Supervisor, Task

(b) Patterns: Strategy, Visitor
Classes: Commander, Regiment, Battalion, Platoon, Soldier, Retreat, Attack, Flank, health checker, supply checker, position checker

(c) Patterns: Adapter
Classes: Clerk, Scale, Standard Scale, Metric Scale

(d) Patterns: Composite
Classes: Program, Package, Class, Method, Field, Interface, Parameter

(e) Pattern: Decorator
Classes: account holder, account, account with overdraft protection, account with free withdrawals if minimum balance maintained.

(f) Pattern: Publisher-Subscriber
Classes: Auction, Auctioneer, Bidder, Item, Seller

(g) Pattern: Publisher, Subscriber
Classes: Room, heater, thermometer, thermostat

(h) Pattern: Composite
Classes: Primitive Type, Array Type, Interface, Map Type, Value, Integer, Integer Type, Null Type

Pattern Matching

2. [5 points each] A pattern catalog contains the following patterns:

A. Publisher-Subscriber, B. Farmer-Chef, C. Adapter
D. Strategy, E. Alarm Clock, F. Abstract Factory
G. Composite, H. Model-View-Controller, I. Proxy
J. Master-Slave

Match the problem with the letter of the pattern that would typically be used to solve it:

i. You need to represent a parse tree created from an XML document.

ii. Employees need to be alerted when meetings on a calendar come up.

iii. A recipe for vegetable soup needs to be independent of the farm that grows the vegetables.

iv. A soldier needs to be able to change battle tactics quickly.

v. Bank customers, employees, and administrators need different user interfaces to the same account manager.

The Virtual Worlds Library

VirtualWorlds (VW) will be a library for game developers.

A virtual world consists of a network of connected sites. A site may be a room or may be a virtual world within a virtual world. For example, a player in a bedroom may step through a secret door into a world of castles, caves, and mazes.

There are two types of VW characters: heroes and their adversaries. A hero moves from site to site. A room may contain adversaries.

a) Draw a UML class diagram showing how you would model these concepts. Consider using the Composite pattern.

The basic VW Adversary class contains methods for attacking and pursuing heroes. The basic attack method involves simply striking the hero:

class Adversary {
   void attack(Hero h) {
      strike(h);
   }
   // etc.
}

Developers will want to enhance the basic attack method. For example, some adversaries may kick before or after striking. Others may sting, still others may bite. We also want to allow combinations, such as kicking twice, then striking, then biting, and finally stinging.

One solution is to create subclasses of Adversary that override the attack method. For example:

class BiteStrikeAdversary extends Adversary {
   void attack(Hero h) {
      bite(h);
      super.attack(h);
   }
   // etc.
}

(b) Assume every combination of biting, stinging, and kicking is to be allowed before and after striking. Ignoring repeats such as biting twice before striking, how many subclasses would we need to provide?

(c) Draw a UML class diagram showing how you could use the Decorator pattern to reduce the number of classes needed to provide the desired combinations.

(d) Draw a UML sequence diagram showing an adversary that bites twice, strikes, and then kicks.

(e) Some adversaries pursue heroes by charging them. Others may sneak up on them. Still others may lure them into traps. In the future, other tactics may be possible. Draw a UML class diagram showing how you would use the Strategy pattern to design this.

(f) Draw a UML object diagram showing an adversary that stings, then strikes and that pursues heroes by luring them into traps.

(g) When a hero enters a room, the monsters will begin pursuing him. Use a UML class diagram to show how the Publisher-Subscriber pattern be used here.

Heroes can ride in vehicles such as tanks and planes. All vehicles can turn, shoot, and move. Several companies provide vehicle models we would like to use. For example, Blaster Inc. provides:

class BlasterT40Tank {
   void drive() { ... }
   void fire() { ... }
   void swivel() { ... }
}

class BlasterF9Jet {
   void drive() { ... }
   void fire() { ... }
   void swivel() { ... }
}

Stealth Inc. provides:

class StealthBattleTank {
   void advance() { ... }
   void blast() { ... }
   void setHeading() { ... }
}

class StealthAttackPlane {
   void advance() { ... }
   void blast() { ... }
   void setHeading() { ... }
}

(h) Use a UML class diagram showing how you could combine the Bridge and Adapter patterns to design the Vehicle hierarchy.

Weather Station

An online weather station requires a thermometer that outputs the average of the temperatures in degrees Fahrenheit of all cities in a given list:

interface IThermometer {
   // = degrees Farenheit
   double getTemperature(List<String> cities);
}

Assume the following class is given:

class CenTherm {
   // = degrees Centigrade
   public double computeTemp(String city) { ... }
}

Show by implementation how would you use the Adapter Pattern to implement the IThermometer interface?

Hint: The formula for converting degrees Centigrade into degrees Fahrenheit is:

F = 1.8 * C + 32

Graphics

A canvas is any instance of a class that implements the following interface:

 interface Canvas {
   Color getcolor(Point p);
   void setColor(Point p, Color c);
}

A color consists of three integers between 0 and 255 representing the amount of red, green, and blue. A point consists of two integers representing the x and y coordinates of the point in some two-dimensional integer coordinate system.

A shape has a color, position, height, and width. The position of a shape is a point representing the upper left corner of the shape's bounding box. Height and width refer to the height and width of the bounding box. A bounding box is the smallest rectangle with sides parallel to the x and y axes that contains the shape.

A shape can plot itself in a specified canvas.

Ellipse and Rectangle are simple shapes. Several shapes may be grouped together to form composite shapes.

Draw a UML class diagram showing how you would use the Composite Pattern to design the Shape Hierarchy.

Implement the CompositeShape class.

Hint: Assume the CompositeShape class has a private helper method called updateBoundingBox. This method sets the position, height, and width of the composite shape based on the position, height, and width of each component shape.

GUIs

Window, Button, and TextBox are all GUI components. A Window contains GUI Components. A Window uses a layout strategy to determine where the components it contains will be placed.

Every component has an upper left corner, a height, a width, and a draw method that takes a GraphicalContext object as a parameter.

Translate this description into a class diagram.

Implement the Component class.

Implement the Window class. (Show as much detail as possible.)

Sports

Basketball, Baseball, and Football are sports. College sports and professional sports are also types of sports. Show how to use the bridge pattern to separate the two classification systems for sports.

Spread Sheet Design

A spread sheet consists of a grid of cells:

Cell[][] sheet = new Cell[M][N];

Each cell has a value that's updated by an update method. The update method may refer to the values of other cells in the sheet to compute its value. A cells update method can be called by the user. It is also called automatically each time any of the cells it depends on are updated.

How would you design and implement the Cell class using the Publisher-Subscriber Pattern?

Unreal Tournament 3000

All fighters in a virtual boxing match must implement the IFighter interface:

interface IFighter {
   void incHealth(); // health++
   void decHealth(); // health--
   int getHealth(); 
}

a. Implement a Fighter class using the Adapter pattern and the following class:

class Warrior {
   private int health = 100;
   public void addHealth(int amt) { health += amt; }
   public void subHealth(int amt) { health -= amt; }
   public int getHealth() { return health; }
}

b. Some fighters are invincible, their health can't be decremented. Some fighters are mighty, incrementing their health makes it go up by two instead of one. Some fighters are mighty and invincible. Some fighters are neither. Implement Decorator, InvincibleDecorator, and MightyDecorator.

c. Show how you would create a mighty, invincible warrior with a single Java statement.

d. A group of monsters attack a hero (see Warrior above). They take turns decrementing the hero's health until the hero dies (health == 0). The monsters must not attempt to decrement the hero's health at the exact same time, and the monsters must be cooperative. Finish the implementation of Monster:

class Monster extends Thread {
   private static Warrior hero = new Warrior();
   // etc.
}

Battlefield Management

A battlefield management system represents soldiers as objects that move and fight. How a soldier moves depends on his orders: retreat, attack, or flank. Here is a proposed design:

problem3

A. Give a one sentence criticism of this design. What design pattern can be used to improve this design?

B. Draw a new class diagram showing how you would use this design pattern to improve the design.

Simplifying a Supply Chain

A supply-chain domain model represents three sellsTo relationships:

problem2

A. Why would the Business class be difficult to implement and use? What design pattern could be used to improve this design?

B. Draw a new class diagram showing how you would use this design pattern to improve the design.

Platform Independence

Most applications require platform services such as file, thread, and window management. Unfortunately, this makes applications platform dependent. Draw a class diagram showing how you would connect the following classes so that porting an application from Windows to UNIX would be relatively painless. (You may add new classes as needed. You do not need to show methods in your diagram, but identify which design patterns you used.)

problem1