Exemplo n.º 1
0
        //Now this piece of code has a problem (it's not extensible)
        //If you provide a framework for processing photos, and suppose a developer using this framework wants to apply a new filter
        //Then you've to create that filter, and recompile and redeploy your code
        //So this problem can be solved with delegates to make this framework extensible
        public void Process(string path)
        {
            var photo = Photo.Load(path);

            var filters = new PhotoFilters();

            filters.ApplyBrightness(photo);
            filters.ApplyContrast(photo);
            filters.Resize(photo);

            photo.Save();
        }
Exemplo n.º 2
0
        public void Call()
        {
            //Without delegates (hence not extensible if we want to apply our own filter as we'll need to change PhotoProcessor class)
            var photoProcessor = new PhotoProcessor();
            photoProcessor.Process("photo.jpg");

            //With custom delegates
            var filters = new PhotoFilters();
            PhotoProcessor.PhotoFilterHandler filterHandler = filters.ApplyBrightness; //Creating an instance of delegate and pointing it to a method having same signature
            filterHandler += filters.ApplyContrast; //As our delegate here is pointing to multiple functions, so this is a multicaste delegate
            filterHandler += RemoveRedEyeFilter;           
            photoProcessor.Process("photo.jpg", filterHandler);

            //With .NET delegates
            Action<Photo> actionFilterHandler = filters.ApplyBrightness;
            actionFilterHandler += filters.ApplyContrast;
            photoProcessor.Process("photo.jpg", actionFilterHandler);
            Action<Photo> action = new Action<Photo>(filters.ApplyBrightness); //Can also call in this way
            action(new Photo());

            UsingInterfaces();
        }