Case study: elevator system
A controller that assigns hall calls and cars that serve their stops in one direction before turning.
Watch it animatedStep through it, with the running line highlighted. Free with an account.The idea
Split "which car" from "how a car moves". The controller asks a dispatch strategy for the best car. Each car keeps stops above and below it in sorted sets and serves one direction completely before turning, like disk SCAN scheduling.
Code
public interface IDispatch { Car Choose(List<Car> cars, int floor); }
public class Controller
{
readonly List<Car> _cars; readonly IDispatch _pick;
public Controller(List<Car> c, IDispatch p) { _cars = c; _pick = p; }
public void HallCall(int floor) => _pick.Choose(_cars, floor).AddStop(floor);
}
public class Car
{
readonly SortedSet<int> _up = new(), _down = new();
public int Floor { get; private set; }
public void AddStop(int f) { if (f > Floor) _up.Add(f); else if (f < Floor) _down.Add(f); }
public void Step() { /* serve _up in order going up, then _down going down */ }
}
public class Door { public bool Open { get; private set; } }Tips
- Dispatch rules (nearest car, least busy, zones) are a Strategy.
- Car modes such as maintenance or emergency fit the State pattern.
- Doors open only when the car is stopped; say that invariant out loud.
In the .NET library
A real system runs each car on its own loop; a Channel<T> per car is a simple way to feed it new stops.