Design Patterns Exercise

In lecture we talked about a number of design patterns. In this exercise you apply them to some small Java examples.

Implementing Patterns

Follow the directions for each section. You may refactor the provided code any way you like as long as you implement the expected patterns.

Start with code in this starter code project for IntelliJ.

a) Telephone: Observer Pattern

The telephone package in the starter project contains partial code for making some parts of a (pretend!) telephone.

Change the code so that it uses the Observer Design Pattern as follows:

  • In the model, define an interface for the observers.
  • Have the model notify the observers whenever a new digit is entered for the phone number.
  • Have the UI (the Screen class) create two observers:
    1. The first observer prints the newest digit out to the screen
    2. The second observer prints "Now dialing 12345678901..." out to the screen (where the number is the number the model has).

Sample output

Constraints

  • Only the UI can print to the screen
  • The model must be decoupled from the UI (model must not know about the UI).


b) Web Search: Strategy Pattern

The websearch package in the starter project contains partial code for a pretend web search engine. It will read a data file and "pretend" that each line is a query someone sent to a search engine. Our goal is to extract, on the fly, "interesting" queries meeting certain conditions.

Note that the code already uses the Observer Pattern to notify the Snooper of each query. The Snooper then prints everything out.

Change the code so that it uses the Strategy Design Pattern as follows:

  • In the model, create a new interface which describes the interface for a policy object that will define a query filter.
  • A query filter policy object will have one method which will be passed a string (the query) and return true if the model should notify the observer about this query; returns false if the observer is not interested in this string (the query). For inspiration, see the Java FileFilter class.
  • Change the model so when an observer is registered, the registration method also accepts a query filter policy object.
  • Change the model so that, for each query (string from the file), the model checks if an observer is interested in the query before notifying it.
  • Change the client (Snooper.java) to create two query observers:
    1. One prints out "Oh yes! <query>" whenever the query contains the word 'friend' (case insensitive).
    2. One prints out "So long....! <query>" whenever the query is more than 60 characters long.

Sample output

Constraints

The model should not know anything about the implementation of the query filter policy objects, other than they implement the required interface.


Submission

This exercise is not for marks: nothing need be submitted.