Module 8 Lab - Traffic Mode (State Pattern)

 

image-20240427-212005.png

 

Code Starter

TrafficState.java

// Defines the interface for various traffic states. Each state must implement methods to calculate ETA and provide directions. public interface TrafficState { int getETA(int distance); String getDirection(int distance); }

DirectionService.java

public class DirectionService { private TrafficState currentState; // Current state of the traffic. private int distance; // Current distance for the trip. // Constructor to initialize the service with a specific traffic state and distance. public DirectionService(TrafficState state, int distance) { this.currentState = state; this.distance = distance; } // Sets the current traffic state, allowing the behavior of getETA and getDirection to change dynamically. public void setTrafficState(TrafficState state) { this.currentState = state; } // Returns the current traffic state, allowing external classes to get information about the current state. public TrafficState getCurrentState() { return currentState; } // Delegates the calculation of ETA to the current state. public int getETA() { return currentState.getETA(distance); } // Delegates the provision of directions to the current state. public String getDirection() { return currentState.getDirection(distance); } // Optionally, a method to update the distance if needed. public void setDistance(int distance) { this.distance = distance; } }

NoTraffic.java

public class NoTraffic implements TrafficState { @Override public int getETA(int distance) { // In no traffic, every mile might take approximately 1 minute to cover. return distance; // Since 1 mile per minute, the ETA is equal to the distance. } @Override public String getDirection(int distance) { // Provides a generic direction for traveling without any traffic delays. return "Proceed straight to your destination, roads are clear."; } }

LowTrafiic.java

MediumTraffic.java

HighTraffic.java

Driver.java

Instructions

implement the code for the HighTraffic and MediumTraffic classes.

MediumTraffic Class:

HighTraffic Class

Driver:

Output Example:

 

image-20240427-214744.png

 Deliverables

Upload the following files in a zip folder that you have created:

  1. Java class files

  2. Screenshot of the Console with the code execution

COSC-1437 / ITSE-2457 Computer Science Dept. - Author: Dr. Kevin Roark