예제 #1
0
    public Car(TrainSignal trainSig, string name)
    {
        Name = name;

        // !!observer pattern!!
        trainSig.TrainsAComing += StopTheCar;
    }
예제 #2
0
        public static void TestUseDelegate()
        {
            TrainSignal trainSignal = new TrainSignal();

            new Car(trainSignal);
            new Car(trainSignal);
            new Car(trainSignal);
            new Car(trainSignal);
            trainSignal.HereComesTheTain();
        }
예제 #3
0
        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);
        }
예제 #4
0
    // 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();
    }
예제 #5
0
 public Car(TrainSignal trainSignal)
 {
     trainSignal.TrainsAreComing += StopTheCar; // construct the list
 }
예제 #6
0
 public void registerToSignal(TrainSignal signal)
 {
     signal.onSignalChange += new lightChangeHandler(respondToSignal);
 }