COMP2511 Week 5

Agenda

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

Admin Stuff

  • Assignment 1 is due this Friday
    • Happy to do interview this week if you're ready 
  • Assignment 2 has been released
    • Get in contact with your partner if you haven't already
  • Lab 05 is due Week 7, Monday 1pm

Strategy Pattern

Strategy Pattern

What is it?

Design pattern that lets you define a family of methods

that are interchangeable at runtime

 

What problem does it solve?

Introduce new behaviours without violating the

Open-Closed principle

 

When should we use this pattern?

When we need multiple ways of achieving the same task

Strategy Pattern

Strategy Pattern

Currently, the code uses switch statements to handle each of the different cases.

 

How does the code violate the open/closed principle?

Strategy Pattern

Currently, the code uses switch statements to handle each of the different cases.

 

How does the code violate the open/closed principle?

  • Not closed for modification / open for extension.
  • Each new case requires a new switch statement.

 

 

Let's refactor it!

Strategy Pattern

Observer Pattern

Observer Pattern

What is it?

Define a subscription mechanism that notifies observers
about any event that happens to the subject that they
are observing

 

What problem does it solve?

Modelling a n-to-many relationship may be difficult. If
not done well, it typically leads to tight coupling

 

When should we use this pattern?

If there is a state that multiple observers are interested in

Observer Pattern

Model the system in Java!

Observer Pattern

 

Find out more at Observer (refactoring.guru)

State Pattern

State Pattern

What is it?

Behavioural design pattern that allows an object to alter its behaviour when its internal state changes.

 

When should we use this pattern?

  • Behaviour differs depending on the current state
  • Be able to switch behaviour at runtime

State Pattern

Text

  • Player has methods that can change its state
  • Behaviour of Player changes based on its state
    • Music is played in the PlayingState 
    • Music is paused in the ReadyState

State Pattern

State Pattern

Find out more at State (refactoring.guru)

Source Code

COMP2511 Tutorial 5

By Matthew Liu

COMP2511 Tutorial 5

  • 112