COMP2511 Week 5

Agenda

  • Admin Stuff
  • Strategy Pattern
  • Observer Pattern
  • State Pattern

Admin Stuff

  • Congratulations on completing your first assignment
  • Interview with me about your assignment in our lab
    • Don't worry it's chill
    • Not marked
    • We will go over your UML and code
    • 5 mins
  • Assignment 2 has been released
  • Everyone should be added to a group on MS Teams
  • Lab 04 is now due Week 5, Friday 5pm
  • Lab 05 is due Week 7, Monday 8am

Strategy Pattern

Strategy Pattern

What is it?

The strategy pattern is a behavioural design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use.

 

 

When should we use this pattern?

  • When we have multiple algorithms to do a specific task
  • When the client decides on the actual implementation to be used at runtime.

Strategy Pattern

Strategy Pattern

Inside src/restaurant is a solution for a restaurant payment system with the following requirements:

  • The restaurant has a menu, stored in a JSON file. Each meal on the menu has a name and price
  • The system displays all of the standard meal names and their prices to the user so they can make their order
  • The user can enter their order as a series of meals, and the system returns their cost
  • The prices on meals often vary in different circumstances. The restaurant has four different price settings:
    • Standard - normal rates

    • Holiday - 15% surcharge on all items for all customers

    • Happy Hour - where registered members get a 40% discount, while standard customers get 30%

    • Discount - where registered members get a 15% discount and standard customers pay normal prices

​The prices displayed on the menu are the ones for standard customers in all settings

  •  

Strategy Pattern

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;
        }
    }
    ...
}

How does the code violate the open/closed principle?
How does this make the code brittle (break easily when updating code)?

Strategy Pattern

Refactor the code to use the Strategy Pattern to handle the four settings.

Here is the strategy interface to get you started:

 

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();

}

Observer Pattern

Observer Pattern

What is it?

The observer pattern is a behavioural design pattern in which an object, named the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

 

When should we use this pattern?

  • When you are interested in the state of an object and want to get notified whenever there is any change.

Observer Pattern

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:

  • A Producer has a name, a series of subscribers and videos
  • When a producer posts a new video, all of the subscribers are notified that a new video was posted
  • A User has a name, and can subscribe to any Producer
  • A video has a name, length and producer

 

 

State Pattern

State Pattern

What is it?

The state pattern is a behavioural software design pattern that allows an object to alter its behaviour when its internal state changes. This pattern is close to the concept of finite-state machines. The state pattern can be interpreted as a strategy pattern, which is able to switch a strategy through invocations of methods defined in the pattern's interface.

 

When should we use this pattern?

  • When objects behave differently depending on the current state.
  • When you want to switch strategy during runtime depending on the current strategy.

State Pattern

State Pattern

Continues from previous exercise/demo. Extend your solution to accommodate the following requirements:

Users can view a video, and a viewing has a series of states:

  • Playing state - the video is playing
  • Ready state - the video is paused, ready to play
  • Locked state - the video is temporarily 'locked' from being watched
Current State Locking Playing Next
Locked If playing, switch to Ready State Switch to Ready State Return error: Locked
Playing Stops playing and switches to Locked State Pauses video and switches to Ready State Starts playing the next video
Ready Changes to locked state Starts playback and changes to playing state Returns Error: Locked (cannot move to next video while paused)
Made with Slides.com