public Car(TrainSignal trainSig, string name) { Name = name; // !!observer pattern!! trainSig.TrainsAComing += StopTheCar; }
public static void TestUseDelegate() { TrainSignal trainSignal = new TrainSignal(); new Car(trainSignal); new Car(trainSignal); new Car(trainSignal); new Car(trainSignal); trainSignal.HereComesTheTain(); }
static void Main() { TrainSignal signal = new TrainSignal(); Train train = new Train(); LevelCrossing crossing = new LevelCrossing(); WarningSiren siren = new WarningSiren(); crossing.registerToSignal(signal); train.registerSignal(signal); siren.registerToSignal(signal); signal.setSignal(signalColour.green); siren.respondToSignal(signalColour.green); signal.setSignal(signalColour.red); siren.respondToSignal(signalColour.red); signal.setSignal(signalColour.green); siren.respondToSignal(signalColour.green); }
// delegates allow references to methods with a matching signature, and can invoke that method through the delegate instanace. // events are delegate references with two restrictions: // you CANT invoke the delegate reference directly // you CANT assign to the delegate reference directly // under the hood, it privatizes the field void Start() { TrainSignal trainSignal = new TrainSignal(); new Car(trainSignal, "Ferrari"); new Car(trainSignal, "Volvo"); new Car(trainSignal, "Bus"); trainSignal.HereComesATrain(); // being NAUGHTY, invoking the delegate directly trainSignal.TrainsAComing(); //being VERY NAUGHTY, nulling out the delegate trainSignal.TrainsAComing = null; // now we loose reference to the delegate trainSignal.HereComesATrain(); }
public Car(TrainSignal trainSignal) { trainSignal.TrainsAreComing += StopTheCar; // construct the list }
public void registerToSignal(TrainSignal signal) { signal.onSignalChange += new lightChangeHandler(respondToSignal); }