Discrete-event simulation is a good option for problems that can be modeled as individual events that take place at specific times. Key activities are:
- randomly generating times and durations based on empirical data, and
- accumulating statistics as the simulation runs.
For example, you could simulate the activity in a parking garage as the entries and departures of a cars and the loss of customers who can't enter because the garage is full. This can be done with two model classes, a Car and the Garage, and three infrastructure classes, an Event class (described below), a Schedule to manage events, and a Monitor to accumulate data.
Here's a brief sketch of how it could work.
Event
An Event has a time, and represents calling a specific method on an object of a specific class.
Schedule
The Schedule keeps a queue of Events, ordered by Event time. The Schedule drives the overall simulation with a simple loop. As long as there are remaining Events (or until the Event that marks the end of the simulation run):
- take the earliest Event from the queue,
- set the "world clock" to the time of that event, and
- invoke whatever action the Event specifies.
Car
The Car class holds the inter-arrival and length-of-stay statistics.
When a Car arrives, it:
logs its arrival with the Monitor,
consults the world clock, determines how long before the next Car should arrive, and posts that arrival Event on the Schedule.
asks the Garage whether it is full:
if full, the Car logs its departure as a lost customer with the Monitor.
if not full, the Car:
logs its entry with the Monitor,
tells the Garage it has entered (so that the Garage can decrease its available capacity),
determines how long it will stay, and posts its departure Event with the Schedule.
When a Car departs, it:
tells the Garage (so the Garage can increase available capacity), and
logs its departure with the Monitor.
Garage
The Garage keeps track of the Cars that are currently inside, and knows about its available capacity.
Monitor
The Monitor keeps track of the statistics in which you're interested: number of customers (successfully-arriving Cars), number of lost customers (who arrived when the lot was full), average length of stay, revenue (based on rate charged for parking), etc.
A simulation run
Start the simulation by putting two Events into the schedule:
the arrival of the first Car (modeled by instantiating a Car object and calling its "arrive" event) and
the end of the simulation.
Repeat the basic simulation loop until the end-of-simulation event is encountered. At that point, ask the Garage to report on its current occupants, and ask the Monitor to report the overall statistics for the session.