用最简单的例子理解策略模式(Strategy Pattern)

当一个动作有多种实现方法,在实际使用时,需要根据不同情况选择某个方法执行动作,就可以考虑使用策略模式。

 

把动作抽象成接口,比如把玩球抽象成接口。

    public interface IBall
    {
        void Play();
    }

有可能是玩足球、篮球、排球等,把这些球类抽象成实现接口的类。

    public class Football : IBall
    {
        public void Play()
        {
            Console.WriteLine("我喜欢足球");
        }
    }
    public class Basketball : IBall
    {
        public void Play()
        {
            Console.WriteLine("我喜欢篮球");
        }
    }
    public class Volleyball : IBall
    {
        public void Play()
        {
            Console.WriteLine("我喜欢排球");
        }
    }   

还有一个类专门用来选择哪种球类,并执行接口方法。

    public class SportsMan
    {
        private IBall ball;
        public void SetHobby(IBall myBall)
        {
            ball = myBall;
        }
        public void StartPlay()
        {
            ball.Play();
        }
    }

客户端需要让用户作出选择,根据不同的选择实例化具体类。

    class Program
    {
        static void Main(string[] args)
        {
            IBall ball = null;
            SportsMan man = new SportsMan();
            while (true)
            {
                Console.WriteLine("选择你喜欢的球类项目(1=足球, 2=篮球,3=排球)");
                string input = Console.ReadLine();
                switch (input)
                {
                    case "1":
                        ball = new Football();
                        break;
                    case "2":
                        ball = new Basketball();
                        break;
                    case "3":
                        ball = new Volleyball();
                        break;
                }
                man.SetHobby(ball);
                man.StartPlay();
            }
        }
    }

1

原文地址:https://www.cnblogs.com/darrenji/p/3959904.html