Lab 08
In this lab session you will practice the practical implementation of two design patterns: the "composite pattern" and the "command pattern".
Preparation
Before you start, I'll walk you through the context. You'll be implementing a mini-drawing application, to illustrate basic figures on the terminal.
We want to be able to define more complex figures, based on primitive elements, and we want to be able to conveniently move figures around, while supporting a command history.
To do so, you will use two design patterns:
- The composite pattern, to define a nested structure of drawable components.
- The command pattern, to ensure reliable adjacent moving of figures and their elements.
Get the code
- Create a new java project.
- Add two packages:
modelandcommand - Download the following files and add them in the corresponding places:
| file | location |
|---|---|
Board.java |
src/model/Board.java |
Component.java |
src/model/Component.java |
Command.java |
src/control/Command.java |
Direction.java |
src/control/Direction.java |
CommandPatternLauncher.java |
src/control/CommandPatternLauncher.java |
ComponentPatternLauncher.java |
src/control/ComponentPatternLauncher.java |
Your project should now look like this:
src
├── command
│ ├── Command.java
│ └── Direction.java
├── CommandPatternLauncher.java
├── ComponentPatternLauncher.java
└── model
├── Board.java
└── Component.java
Composite pattern
In this first exercise, it is your job to make the ComponentPatternLauncher work.
To paraphrase, this class will do the following:
- Create a new square (consisting of 4
x).
- Move the square around.
- Create a new triangle (consisting of 3
x).
- Move the triangle around.
- Group square and triangle to form a "house", move the house around
Your turn
Create new classes to complete the Composite pattern, so the provided launcher ode runs and prints as expected. Do
not modify the launcher.
Command pattern
The previous code worked, but left no option to undo (or redo) actions. Most interactive programs maintain a history of
executed commands, to allow convenient correction of choices. The CommandPatternLauncher imitates this principle, by
representing all actions via Command objects, that:
- Enforce following the rules (we stipulate that a figure must only be moved my one adjacent field at a time).
- Allow conveniently reverting previously executed actions.
In detail the provided code does the following, using dedicated commands:
- Create a new square shaped figure
- Move square one adjacent field down.
- Undo the last command.
- Redo the last command.
- Add a triangle as separate component (superposition).
- Group square and triangle to form a house.
- Move the house as a whole to the right.
- Undo the last command (move).
Your turn
Implement the required commands. For moving, you can define a single move command that receives a Direction as
constructor argument.
Verify your code prints the expected output. Do not modify the launcher.