25T1 Week 10 🥳
Thursday 9am-12pm (H09B)
Slides by Sam Zheng (z5418112)
Original slides by Alvin Cherk
MyExperience ->
Please fill it in (5 mins)
Creational Pattern
public class Car {
private String engine;
private int wheels;
private boolean sunroof;
private String color;
private boolean gps;
public Car(String engine, int wheels, boolean sunroof, String color, boolean gps) {
this.engine = engine;
this.wheels = wheels;
this.sunroof = sunroof;
this.color = color;
this.gps = gps;
}
@Override
public String toString() {
return "Car{" + "engine=" + engine + ", wheels=" + wheels +
", sunroof=" + sunroof + ", color=" + color + ", gps=" + gps + '}';
}
}
// Usage
Car car = new Car("V8", 4, true, null, false);
Car car2 = new Car("I4", 4, false, "red", true);
// Not every car will use every parameter, and this could get very long with more complex objects!
Consider this example:
public class Car {
private String engine, color;
private int wheels;
private boolean sunroof, gps;
private Car(Builder b) {
this.engine = b.engine;
this.wheels = b.wheels;
this.sunroof = b.sunroof;
this.color = b.color;
this.gps = b.gps;
}
public static class Builder {
private String engine, color = "white";
private int wheels = 4;
private boolean sunroof = false, gps = false;
public Builder engine(String engine) { this.engine = engine; return this; }
public Builder sunroof(boolean sunroof) { this.sunroof = sunroof; return this; }
public Builder color(String color) { this.color = color; return this; }
public Builder gps(boolean gps) { this.gps = gps; return this; }
public Car build() { return new Car(this); }
}
}
// Usage - you don't have to specify all parameters, only call methods you need/want!
Car car = new Car.Builder()
.engine("V8")
.gps(true)
.build();In our system, we have trains which contain many engines and/or wagons. As in a normal train, these engines/wagons are ordered sequentially from the front of the train to the back.
Engines provide a certain amount of power and wagons require a certain amount of power to pull. At each point along the train, taking into account preceeding engines/wagons, the sum of the engine power must be greater than the sum of the wagon's required power. Otherwise, the rest of the train will be left behind!
There are three types of wagons:
Create a train builder that constructs a train in order, wagon by wagon with the above constraint. If the above constraint is violated at any point, throw an IllegalStateException.