24T3 Week 7
Tuesday 3PM - 6PM (T15A)
Thursday 11AM - 2PM (H11C)
Slides by Christian Tolentino (z5420628)
What type of design pattern is composite?
Structural
Structural design pattern are patterns that ease the design by identifying a simple way to realize relationships among entities.
They explain how to assemble objects and classes into large structures, while keeping structures flexible and efficient
Composite pattern is useful for aggregating different objects/data. The aim is to be able to manipulate a single instance of an object just as you would manipulate a group of them.
Tree like structure of objects
Calculator.java - Composite pattern
Inside src/calculator, use the Composite Pattern to write a simple calculator that evaluates an expression. Your calculator should be able to:
{1 + [2 * (4 + 3)]}
Expression 1
Expression 2
Expression 3
What type of design pattern?
Creational
Creational patterns provide various object creation mechanisms, which increase flexibility and reuse of existing code.
Factory method provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.
Reduces coupling and shotgun surgery, as all classes are created using the same method.
Thrones.java - Factory Pattern
Inside src/thrones, there is some code to model a simple chess-like game. In this game different types of characters move around on a grid fighting each other. When one character moves into the square occupied by another they attack that character and inflict damage based on random chance. There are four types of characters:
We want to refactor the code so that when the characters are created, they are put in a random location in a grid of length 5.
main method of Game.java to use these factories.What type of design pattern?
Behavioural
Behavioural patterns are patterns concerned with algorithms and the assignment of responsibility between object
The decorator pattern allows you to dynamically add new behaviours or responsibilities to objects without modifying their existing code.
Gives code more flexibility, reduces coupling and separates functionality into smaller, reusable classes (single-responsibility)
Thrones.java - Factory Pattern
Suppose a requirements change was introduce that necessitated support for different sorts of armour.
Use the Decorator Pattern to realise these new requirements. Assume that, as this game takes place in a virtual world, there are no restrictions on the number of pieces of armour a character can wear and that the "order" in which armour is worn affects how it works. You may need to make a small change to the existing code.