策略模式学习总结

目录

策略模式

引言

定义

模式结构图

实例

实例说明

实例类图

代码实现

总结

模式优点

模式缺点 


策略模式

引言

策略模式对应于解决某一问题的一个算法族,允许用户从该算法族中任选一个算法解决某一个问题,同时可以方便地更换或者增加新的算法。

定义

英文定义:“Define a family of algorithms,encapsulate each one,and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it”。

中文定义:定义一系列算法,将每一个算法封装起来,并让他们可以互相替换。策略模式让算法独立于使用·它们的客户而变化。

                                            策略模式重要等级★★★★☆     策略模式难度等级★★☆☆☆ 

模式结构图

实例

实例说明

旅游出行可以有多种,可以坐飞机,可以乘火车,还可以骑自行车。使用策略模式来模拟这一过程。

实例类图

代码实现

环境类Person

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


class Person
{
    private TravelStrategy strategy;

    internal TravelStrategy Strategy
    {
        get
        {
            return strategy;
        }

        set
        {
            strategy = value;
        }
    }

    public void Travel()
    {
        strategy.Travel();
    }
}

策略接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

interface TravelStrategy
{
    void Travel();
}

具体策略类Airplan

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


public class AirPlanStrategy : TravelStrategy
{
    public void Travel()
    {
        Console.WriteLine("灰机出行。");
    }
}

具体策略类Train

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


class TrainStrategy : TravelStrategy
{
    public void Travel()
    {
        Console.WriteLine("火车出行。");
    }
}

具体策略类Bicyle

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


class BicyleStrategy : TravelStrategy
{
    public void Travel()
    {
        Console.WriteLine("自行车出行.");
    }
}

测试代码

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading;

class Program
{
    static void Main(string[] args)
    {
        Person p = new Person();

        //这一行代码可以做到配置文件,即可动态选择策略
        p.Strategy = new AirPlanStrategy();

        p.Travel();
        Console.ReadKey();
    }
}

运行截图

总结

模式优点

1)策略模式提供了对“开闭原则”的完美支持,用户可以在不修改原有的系统的基础上选择算法或行为,也可以灵活的增加新的算法或行为。

2)策略模式提供了管理相关的算法族的方法。策略类的等级结构定义了一个算法或者行为族,恰当使用继承可以把公共的代码移到父类里,从而避免重复的代码。

3)使用策略模式可以减少使用多重条件转移语句(if else)

模式缺点 

1)客户端必须知道所有策略类,并自行决定使用那个策略类。

2)策略模式将造成产生很多策略类和对象。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值