策略模式是对算法的封装,是把算法的接口和算法的实现分割开来,通过延迟实现具体的算法,通过增加新的算法类,而不用修改已有的代码,来提高代码的扩展性。

  打游戏有两种策略,一种是打多塔,一种是玩LOL,通过策略模式,可以通过增加新类来实现新的策略。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        /// <summary>
        /// 打游戏的接口
        /// </summary>
        public interface IPlayGame
        {
            void PlayGame();
        }

        /// <summary>
        /// 打dota
        /// </summary>
        public class PlayDota : IPlayGame
        {
            public void PlayGame()
            {
                Console.WriteLine("play dota");
            }
        }


        /// <summary>
        /// 打LOL
        /// </summary>
        public class PlayLOL : IPlayGame
        {
            public void PlayGame()
            {
                Console.WriteLine("play lol");
            }
        }

        public class Person
        {
            public IPlayGame PlayGame
            {
                get;
                set;
            }

            public Person(IPlayGame playGame)
            {
                PlayGame = playGame;
            }

            public void Action()
            {
                PlayGame.PlayGame();
            }
        }

        static void Main(string[] args)
        {
            Person person = new Person(new PlayDota());
            person.Action();

            person.PlayGame = new PlayLOL();
            person.Action();
        }
    }
}