C#设计模式-策略模式

本文介绍了一个使用C#实现的策略模式示例,通过创建不同的策略类(如AggressiveBot和DefensiveBot),并在AIContext上下文中切换这些策略,展示了如何在运行时改变对象的行为。策略模式允许在不修改客户端代码的情况下更改算法或行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();
            }
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值