mardi 21 mai 2019

How implement a delegation pattern in c# using delegates?

I want to implement delegation pattern using delegates

public class Cat {
    private delegate void SoundDelegate();
    private SoundDelegate sound;
    public Cat() {
        sound = new SoundDelegate(SomeClass.DoSound1);
    }
    public void DoSound() {
        sound();
    }
}
public class PussyCat {
    private delegate void SoundDelegate();
    private SoundDelegate sound;
    public PussyCat() {
        sound = new SoundDelegate(SomeClass.DoSound2);
    }
    public void DoSound() {
        sound();
    }
}
public class SomeClass {
    public static void DoSound1() {
        Console.WriteLine("Sound 1");
    }
    public static void DoSound2() {
        Console.WriteLine("Sound 2");
    }
}

Does this code impelement the delegation pattern? I mean can I use delegates for implement delegation pattern or this way is incorrect.

And if the previous example is correct and I can use delegates to implement the delegation pattern and implement the observer pattern, then what is the difference between the observer pattern and the delegation pattern and what is similar?

Aucun commentaire:

Enregistrer un commentaire