23T2 Week 5
Wednesday 1PM - 4PM (W13A)
Thursday 3PM - 6PM (H15B)
Slides by Alvin Cherk (z5311001)
You have an assignment viva in your next lab.
You must come to the Week 7 lab. If you cannot, please email me.
Problem: Only some of the children of a parent class implement an abstract method the same way.
Question: How would you implement this without duplicating code?
Note: Behaviours are only shared downwards in inheritance
Problem: Only some of the children of a parent class implement an abstract method the same way.
We could introduce a new class in-between the parent and child class.
We could introduce a new class in-between the parent and child class.
However, this becomes problematic when we the Ducks have other methods that share the same implementation.
A solution is to move this behaviour into another class and compose this class inside Duck
This is one of the main benefits of the strategy pattern, sharing behaviour across an inheritance tree
What type of design pattern is strategy?
Behavioural Pattern
Behavioural patterns are patterns concerned with algorithms and the assignment of responsibility between object
Strategy Pattern
Restaurant payment system with the following requirements:
The prices displayed on the menu are the ones for standard customers in all settings
public class Restaurant {
...
public double cost(List<Meal> order, String payee) {
switch (chargingStrategy) {
case "standard":
return order.stream().mapToDouble(meal -> meal.getCost()).sum();
case "holiday":
return order.stream().mapToDouble(meal -> meal.getCost() * 1.15).sum();
case "happyHour":
if (members.contains(payee)) {
return order.stream().mapToDouble(meal -> meal.getCost() * 0.6).sum();
} else {
return order.stream().mapToDouble(meal -> meal.getCost() * 0.7).sum();
}
case "discount":
if (members.contains(payee)) {
return order.stream().mapToDouble(meal -> meal.getCost() * 0.85).sum();
} else {
return order.stream().mapToDouble(meal -> meal.getCost()).sum();
}
default:
return 0;
}
}
...
}
Not closed for modification, open for extension. If more cases need to be added, the switch statement has to be changed.
New requirements may cause the code to break or may be difficult to implement
public class Restaurant {
...
public void displayMenu() {
double modifier = 0;
switch (chargingStrategy) {
case "standard":
modifier = 1;
break;
case "holiday":
modifier = 1.15;
break;
case "happyHour":
modifier = 0.7;
break;
case "discount":
modifier = 1;
break;
}
for (Meal meal : menu) {
System.out.println(meal.getName() + " - " + meal.getCost() * modifier);
}
}
...
}
Similar idea here, if new cases need to be added, the class's method itself needs to be changed. Cannot be extended
To fix these issues, we can introduce a strategy pattern and move all the individual case logic into their own classes
public interface ChargingStrategy {
/**
* The cost of a meal.
*/
public double cost(List<Meal> order, boolean payeeIsMember);
/**
* Modifying factor of charges for standard customers.
*/
public double standardChargeModifier();
}
The prices on meals often vary in different circumstances. The restaurant has four different price settings:
What type of design pattern is strategy?
Behavioural Pattern
An object (subject) maintains a list of dependents called observers. The subject notifies the observers automatically of any state changes.
Observer
Subject
Observer Pattern
In src/youtube
, create a model for the following requirements of a Youtube-like video creating and watching service using the Observer Pattern:
What type of design pattern is strategy?
Behavioural Pattern
Allows an object to alter its behaviour at run-time when its internals state changes.
State Pattern
Continues from previous exercise/demo.
Extend your solution to accomodate the following requirements:
Current \ Input | Locking | Playing | Next |
---|---|---|---|
Locked | If playing, switch to ready state, else locked | Switch to ready state | Return error: Locked |
Playing | Stops playing, switch to locked | Pauses video, switch to ready | Starts playing next video |
Ready | Go to locked | Start playback, change to play state | Returns error: Locked |
package youtube.state;
import youtube.Viewing;
public abstract class ViewingState {
private Viewing viewing;
public ViewingState(Viewing viewing) {
this.viewing = viewing;
}
public abstract String onLock();
public abstract String onPlay();
public abstract String onNext();
public Viewing getViewing() {
return this.viewing;
}
}
public class Viewing {
private Video video;
private Video nextVideo;
private Producer user;
private ViewingState state = new ReadyState(this);
private boolean playing = false;
public Viewing(Video video, Video nextVideo, Producer user) {
this.video = video;
this.nextVideo = nextVideo;
this.user = user;
}
public void setPlaying(boolean play) {...}
public boolean isPlaying() {...}
public void changeState(ViewingState newState) {...}
public String startPlayback() {...}
public String getNextVideo() {...}
public String lock() {...}
public String play() {...}
public String next() {...}
}
State Interface/Abstract Class