Behavioral Patterns  «Prev  Next»

Observed Object - Exercise

An Observed Object

Objective:Write a Time class as an Observed object.
Rewrite the Time class from Module three so that it adheres to both the Singleton and the Observed pattern. This class should simply count seconds for an amount of time given in the constructor. Each second, it should notify registered observers of the current time using their timeChanged() method. When you are finished, the class should look like this:

Time class with methods currentTime, endOfTime, getInstance, init, run(), addTimeObserver, removeTimeObserver
The class diagram provided represents a `Time` class. Here's the detailed breakdown:
  1. Data Members:
    • currentTime : int:
      • Stores the current time, likely as an integer value.
    • endOfTime : int:
      • Represents the end time or a limit for the time, also stored as an integer.
  2. Methods:
    • -Time(endOfTime : int):
      • A private constructor for the Time class, initializing the endOfTime attribute. This suggests that the class follows a singleton pattern, as the constructor is not public.
    • +getInstance() : Time:
      • A public method to get the single instance of the Time class. This is typical in the Singleton design pattern.
    • +init(endOfTime : int) : void:
      • A public method to initialize the Time instance, possibly setting the value of endOfTime.
    • +run() : void:
      • Likely starts or continues the time-related logic (e.g., incrementing currentTime or managing the flow of time).
    • +addTimeObserver(timeObserver : TimeObserver) : void:
      • Allows an external TimeObserver to register as an observer to the Time class. Observers will likely be notified of changes in the time.
    • +removeTimeObserver(timeObserver : TimeObserver) : void:
      • Removes a previously registered TimeObserver, stopping it from receiving time updates.

Purpose: The `Time` class appears to act as a Singleton Subject in an Observer Design Pattern. It ensures that there is only one instance of `Time`, and it maintains a list of observers (`TimeObserver`) that are notified when the time changes.
Time class with methods currentTime, endOfTime, getInstance, init, run(), addTimeObserver, removeTimeObserver

The run() method increments the currentTime, and notifies each registered listener of that change.
In the text area below, type your answer and click the Submit button.