C#设计模式-策略模式

using System;
using System.Collections.Generic;

namespace TestCSharp
{
    class Program
    {
        // client needs to know the state in the strategy mode. while in the state mode, it is no need to know. 
        static void Main(string[] args)
        {
            AIContext context = new AIContext();
            context.CurStrategy = new AggressiveBot();
            context.Execute();

            context.CurStrategy = new DefensiveBot();
            context.Execute();

            Console.ReadKey();
        }

        abstract class Strategy
        {
            public abstract void Execute();
        }

        class AggressiveBot : Strategy
        {
            public override void Execute()
            {
                Console.WriteLine("Attack");
            }
        }

        class DefensiveBot : Strategy
        {
            public override void Execute()
            {
                Console.WriteLine("Defense");
            }
        }

        class AIContext
        {
            public Strategy CurStrategy{ set; get; }

            public void Execute()
            {
                if (CurStrategy == null)
                {
                    return;
                }
                CurStrategy.Execute();
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_37273889/article/details/85061673