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.
Suggestion: Create these classes using StarUML, then use the "Apply Pattern" tool to assign rolls to the classes.
(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: Model-View-Controller, Publisher, Subscriber
Classes: Room, heater, thermometer, thermostat
(h) Patterns: Model-View-Controller, Publisher-Subscriber
Classes: Vehicle, Engine, Tachometer, Dashboard, steering wheel, Oil Gauge,
Temperature Gauge, Speedometer, Compass, Pedal, Brake, Accelerator
(i) Patterns:
Model-View-Controller
Classes: Tracking station, guidance system, satellite
(j) Patterns: Model-View-Controller, Command Processor,
Memento
Classes: Transaction, Command, Undoable Command, Database, Database Management
System, Database Browser
(k) Patterns: Mediator
Classes: Bus, Processor, RAM, DMA Controller
(l) Patterns: Model-View-Controller, Strategy, Decorator
Classes: Slide Show, Slide, Transition, Applause, Whoosh, Dissolve, Wipe Left,
Wipe Down, Full Screen View, Sorter View, Normal View
(m) Patterns: Bridge, Adapter, Gateway
Classes: Gateway, Query, Update, MySQL Driver, Oracle
Driver, MySQL DBMS, Oracle DBMS
(n) Pattern: Composite
Classes: Primitive Type, Array Type, Interface, Map Type, Value, Integer,
Integer Type, Null Type
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 object 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.
All of the methods and fields of a utility class are static. There is no point in creating instances of a utility class. For example, Java's Math class is a utility class containing standard mathematical functions:
class Math {
public static double sin(double x) {
... }
public static double cos(double x) {
... }
public static double log(double x) {
... }
// etc.
}
Only one instance of a singleton class can be created. Often a developer can choose between a utility class and a singleton class.
For example, a white page server contains a hash table that associates server names to server locations. The white page server provides a method that allows servers to register their names and locations, and provides a method that allows clients to locate servers using only their names. Of course all servers and clients will somehow need to know where the white page server is located. It might be confusing if an application has more than one white page server.
Here are the possible designs. First using Singleton:
Second, using a utility class:
UML note: An underlined method or field is static.
(a) Sketch an implementation of WhitePageServer, Server, and Client two times. In both cases your sketch should show how the client and server use the white page server. First implement WhitePageServer as a utility class, and then as a singleton class.
(b) Can you think of any advantages or disadvantages of singleton over utility or vice-versa?
We can have many non-mutable objects representing the same real world object because there's no danger that they will get out of synch with each other. For example, it's not a problem having multiple non-mutable Student objects representing the same student.
Having several mutable Student objects representing the same student is a problem, however, because they can be mutated in different ways and therefore become out of synch with each other.
Use interning to implement a mutable Student class that doesn't allow two student objects to be created that represent the same student.
Criticize the following designs
(a)
(b)
(c)
(d)
(e)
(f)
1. 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
2. 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.
3. 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.)
4. 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.
5. Sometimes, in early development, a "mock" object is needed so that testing can proceed while the real object is under development. A mock object implements the same interface as the object that will replace it.
A gateway has the following interface:
interface Gateway {
Model getModel(String fname) throws
AppError;
void saveModelAs(Model model, String
fname) throws AppError;
void saveModel(Model m) throws AppError;
}
Where:
class Model implements Serializable {
String fname = null; // name of file
where this model is stored
boolean usavedChanges = false; // true
if modified since last save
}
Eventually, this interface will be implemented by an object that interfaces with a database system. For now, create a mock object that uses a hashtable to store models and their names.
6. There should be only on instance of a GUI. Show how you would use the Singleton pattern in the GUI class.
Show how you would design the following system using UML class diagrams and design patterns.
A chess playing program allows multiple users to play chess against a centralized server. Users can save their games and resume them later.
Your team is developing an application that will create, browse, and update student records that will be stored in some sort of database. A student record contains a last name, first name, unique id number, major, and a GPA. Using the DAO and Transfer Object patterns develop an interface that the application can use to access the database. Your DAO should allow searches that return multiple records. (Hint: a null field matches anything.)
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?
After a student has been admitted to
Draw a domain model using a class diagram.
Draw a use case diagram.
How would you design STS? Consider using the following patterns: Three-Tier architecture, Model-View-Controller, Proxy, Gateway, and Transfer Objects.
Implement a student record in Java.
When a patient checks into the hospital, the hospital administrator creates a patient record in the Patient Tracking System (PTS). The record initially holds the patient's name, the name of his insurance company, his policy identification number, and the name of his doctor. After the patient has been admitted, his doctor places orders for tests on the patient's record. These tests are performed by technicians, who record the results in the patient record. Next the doctor orders treatments by placing them in the patient record. Nurses perform the treatment. When the patient checks out of the hospital, the administrator adds up the costs for the tests and treatments and generates an invoice.
Draw a UML class diagram showing how you would model this domain.
Write an interface for a DAO that transfers patient records between a database and the PTS using transfer objects.
A claims processing system (CPS) provides a user interface that allows a claims adjuster to view and update policies, and to create, update, and view claims. When a claims adjuster receives an accident report, he first determines if the accident will be covered by the claimant's policy. If so, he creates a claim that describes the date of the claim and the policy number of the claimant. After the adjuster receives three repair estimates and a police report, a check is issued to the claimant, the claim is closed. The amount of the check is determined by the business rule:
lowest estimate - deductable
If, according to the police report, the claimant was at fault, then the policy premium is increased according to the business rule:
premium += riskFactor * premium
where
riskFactor =
(#claims where the claimant was at
fault)/# of years driving
Represent the description just given with a UML activity diagram.
Draw a UML diagram showing how you would design this system. Consider using the Model-View-Controller and DAO patterns.
Write an interface for a DAO that uses transfer objects to move claims and policies between the CPS and the database.