25T2 Week 7
Friday 1-2pm (F13A)
Start 1:05pm
By: Sam Zheng (z5418112)
What type of pattern?
Creational pattern
The singleton pattern ensures that a class has only one instance. It provides a global access point to this instance.
It helps avoid initialisation overhead when only 1 copy of an instance is needed.
Heist.java
// Abstract Products
interface Button { void render(); }
class LightButton implements Button { public void render() { System.out.println("🟡 Light Button"); } }
class DarkButton implements Button { public void render() { System.out.println("⚫ Dark Button"); } }
// Abstract Factory
interface GUIFactory { Button createButton(); }
class LightFactory implements GUIFactory { public Button createButton() { return new LightButton(); } }
class DarkFactory implements GUIFactory { public Button createButton() { return new DarkButton(); } }
// Client Code
public class AbstractFactoryExample {
public static void main(String[] args) {
GUIFactory factory = new DarkFactory(); // Switch to LightFactory for light mode
factory.createButton().render(); // ⚫ Dark Button
}
}Thrones.java Part 1 - Abstract Factory Pattern
We want to simulate the board game with the added change that pieces can be made from different materials, either Wood, Plastic or Metal. We want to be able to pick and choose which material we create a board with. Each material has its own construction requirements:
0 <= x <= 5, and y = 0
bound (provided to the factory)nxn grid, meaning they can only be placed on tiles with x and y values which divide n (n is provided to the factory)interface Coffee { double cost(); }
// Concrete Component
class SimpleCoffee implements Coffee {
public double cost() { return 5.00; }
}
// Decorator
abstract class CoffeeDecorator implements Coffee {
protected Coffee coffee;
public CoffeeDecorator(Coffee coffee) { this.coffee = coffee; }
public double cost() { return coffee.cost(); }
}
// Concrete Decorators
class MilkDecorator extends CoffeeDecorator {
public MilkDecorator(Coffee coffee) { super(coffee); }
public double cost() { return coffee.cost() + 1.50; }
}
class SugarDecorator extends CoffeeDecorator {
public SugarDecorator(Coffee coffee) { super(coffee); }
public double cost() { return coffee.cost() + 0.75; }
}
public class DecoratorExample {
public static void main(String[] args) {
Coffee coffee = new SimpleCoffee();
coffee = new MilkDecorator(coffee);
coffee = new SugarDecorator(coffee);
System.out.println("Total cost: $" + coffee.cost()); // $7.25
}
}Thrones.java Part 2 - Decorator Pattern
Now we want our game to support adding different armour types for our pieces:
We can use the Decorator Pattern implement this really easily!