strategy pattern

//-------------STRATEGY PATTERN-------------//

using System;

namespace Patterns_Ducks
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Mallock Duck");
            Duck md = new MallockDuck();
            md.PerformFly();

            md.SetFlyBehavior(new FlyNoWay());
            md.PerformFly();

            //RubberDuck rd = new RubberDuck();
            //rd.PerformFly();
            DuckCall dc = new DuckCall();
            dc.PerformFly();
        }
    }

    public interface Ifly
    {
        void Fly();
    }

    public class FlyWithWings : Ifly
    {
        #region Ifly Members
        public void Fly()
        {
            Console.WriteLine("Flying with wings");
        }
        #endregion
    }

    public class FlyNoWay : Ifly
    {
        #region Ifly Members
        public void Fly()
        {
            Console.WriteLine("Fly no way");
        }
        #endregion
    }

    public abstract class Duck
    {
        public Ifly objfly;
        public void PerformFly()
        {
            objfly.Fly();
        }
        public void SetFlyBehavior(Ifly obj)
        {
            objfly = obj;
        }
        public void Quack()
        {
            Console.WriteLine("quack");
        }
        public void Swim()
        {
            Console.WriteLine("swim");
        }
        public void Display()
        {
            Console.WriteLine("display");
        }
    }

    public class MallockDuck : Duck
    {
        public MallockDuck()
        {
            objfly = new FlyWithWings();
        }
    }
    public class RubberDuck : Duck
    {
        public RubberDuck()
        {
            objfly = new FlyNoWay();
        }
    }

    public class DuckCall
    {
        Ifly objFly;
        public DuckCall()
        {
            objFly = new FlyWithWings();
        }
        public void PerformFly()
        {
            objFly.Fly();
        }
    }
}

Ebook Download
View all
Learn
View all