.NET类库中发现设计模式:策略模式
策略模式:
The Strategy Pattern defines a family of algorithms,encapsulates each one,and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.(策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。)
Context(应用场景):
需要使用ConcreteStrategy提供的算法。
内部维护一个Strategy的实例。
负责动态设置运行时Strategy具体的实现算法。
负责跟Strategy之间的交互和数据传递。
Strategy(抽象策略类):
定义了一个公共接口,各种不同的算法以不同的方式实现这个接口,Context使用这个接口调用不同的算法,一般使用接口或抽象类实现。
ConcreteStrategy(具体策略类):
实现了Strategy定义的接口,提供具体的算法实现。
废话少说,到.NET类库中找找策略模式
ArrayList类肯定都会用过吧,那么它的Sort方法想必大家也一定不陌生了。Sort方法的定义如下:
public virtual void Sort (IComparer comparer)
可以看到Sort方法接收一个IComparer类型的参数,那么这个IComparer接口是做什么用的呢?下面我们看一段程序,下面的代码示例演示如何使用默认比较器和一个反转排序顺序的自定义比较器,对ArrayList 中的值进行排序:
using System;
using System.Collections;
public class SamplesArrayList
{
public class myReverserClass : IComparer
{
// Calls CaseInsensitiveComparer.Compare with the parameters reversed.
int IComparer.Compare(Object x, Object y)
{
return ((new CaseInsensitiveComparer()).Compare(y, x));
}
}
public static void Main()
{
// Creates and initializes a new ArrayList.
ArrayList myAL = new ArrayList();
myAL.Add("The");
myAL.Add("quick");
myAL.Add("brown");
myAL.Add("fox");
myAL.Add("jumps");
myAL.Add("over");
&n
相关新闻>>
- 发表评论
-
- 最新评论 进入详细评论页>>
今日头条
更多>>您可能感兴趣的文章
- asp.net js模拟Button点击事件
- Pro ASP.NET MVC 3 Framework学习笔记之九
- 教你如何来恢复一个丢失的数据文件
- 谈.Net委托与线程——创建无阻塞的异步调用(一
- Asp.net MVC源码分析--Model Validation(Client端)实现(2)
- MVC中一个表单实现多个提交按钮(一个action搞定
- ASP.NET数据格式的Format--DataFormatString
- winform下通过webclient使用非流方式上传(post)数据和
- asp.net 六大内置对象(2)
- 微软ASP.NET站点部署指南(11):部署SQL Server数据