关于.NET Framework中的设计模式--应用策略模式为List排序

发布时间:2022-04-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了关于.NET Framework中的设计模式--应用策略模式为List排序脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
简单类型排序

编程时遇到排序在平常不过,使用.Net最常见的就是对泛型List<T>进行排序,如果T是简单数据类型排序那么很简单

复制代码 代码如下:

public List<int> SortSimpleList(List<int> list)
{
list.sort();
return list;
}

同样对string等简单类型List<T>排序均如此,如果我们要排的对象复杂了怎么办,我们知道List<T> sort()最后是用快速排序实现,快速排序也好,什么排序都需要知道list中ITem之间的比较结果,如果是简单的int类型,直接判断即可,对实现了IComparable接口的对象,可以调用其CompareTo()实现item比较大小,下面是一个快速排序的写法

复制代码 代码如下:

void Sort<T>(T[] array, int left, int right, IComparer_sly<T> comparer) where T : IComparable
{
if (left < right)
{
T middle = array[(left + right) / 2];
int i = left - 1;
int j = right + 1;
while (true)
{
while (array[++i].COMpareTo(middle) < 0) ;

while (array[--j].CompareTo(middle) > 0) ;

if (i >= j)
break;

T temp = array[i];
array[i] = array[j];
array[j] = temp;
}

Sort(array, left, i - 1, comparer);
Sort(array, j + 1, right, comparer);
}
}

问题

对于前两种情况固然可以实现排序,但是我们不可能要求所有待排序的对象都实现IComparable接口,就算能够保证每个对象都实现IComparable接口,如果想实现对象内多个字段排序,比如Student对象,有时候想按照姓名排序,有时候是成绩,有时候是年龄,这怎么破

按照面向对象的思想,要把变化独立出来,封装变化,对于我们排序List<T>时变化的其实就是怎么比较两个对象的大小的算法,如果我们可以把这个算法拿出来,排序就简单了很多,无论什么排序,算法都是由的,我们要封装的部分是怎样比较两个item的大小的算法,为了实现拓展性我们要遵循面向对象设计的另外一个重要原则,针对接口编程,而不是针对实现编程。

编写通用的List<T>排序方法

首先定义一个接口,里面有一个比较item大小的方法,在排序的时候作为参数传入,当然是传入它的实现类,有了这个想法,我们可以自己写个List<T>的排序方法

复制代码 代码如下:

public interface mparer_sly<T>{
int Compare(T x, T y);
}

然后为了测试,我们为List<T>加一个包装,写一个自己的Sort方法,内部也用快速排序实现。一直困惑我们的变化部分——比较大小算法,我们把它封转起来,作为参数传入

复制代码 代码如下:

using System;
using System.Collections.Generic;

namespace test.stategy
{public class ListTest<T>
{
public List<T> list = new List<T>();
public void Sort(IComparer_sly<T> comparer)
{
T[] array = list.ToArray();
int left = 0;
int right = array.Length - 1;
Quicksort(array, left, right, comparer);
list = new List<T>(array);
}

PRivate void QuickSort<S>(S[] array, int left, int right, IComparer_sly<S> comparer)
{
if (left < right)
{
S middle = array[(left + right) / 2];
int i = left - 1;
int j = right + 1;
while (true)
{
while (comparer.Compare(array[++i], middle) < 0) ;

while (comparer.Compare(array[--j], middle) > 0) ;

if (i >= j)
break;

S temp = array[i];
array[i] = array[j];
array[j] = temp;
}

QuickSort(array, left, i - 1, comparer);
QuickSort(array, j + 1, right, comparer);
}
}
}
}

比如现在我们有个Student 的实体

复制代码 代码如下:

public class Student
{
public Student(int id, string name)
{
this.ID = id;
this.Name = name;
}
public int ID { get; set; }
public string Name { get; set; }
}

如果想对这个实体组成的List<T>进行排序,我们只需一个实现 IComparer_sly<Student>的类 StudentComparer,并在内部实现其比较大小方法——Compare(),同时我们可以添加递增还是递减排序的控制

复制代码 代码如下:

class StudentComparer : IComparer_sly<Student>
{
private string exPression;
private bool isAscending;
public StudentComparer(string expression, bool isAscending)
{
this.expression = expression;
this.isAscending = isAscending;
}

public int Compare(Student x, Student y)
{
object v1 = GetValue(x), v2 = GetValue(y);
if (v1 is string || v2 is string)
{
string s1 = ((v1 == null) ? "" : v1.ToString().Trim());
string s2 = ((v2 == null) ? "" : v2.ToString().Trim());
if (s1.Length == 0 && s2.Length == 0)
return 0;
else if (s2.Length == 0)
return -1;
else if (s1.Length == 0)
return 1;
}

// 这里就偷懒调用系统方法,不自己实现了,其实就是比较两个任意相投类型数据大小,自己实现比较麻烦
if (!isAscending)
return Comparer.Default.Compare(v2, v1);
return Comparer.Default.Compare(v1, v2);
}

private object GetValue(Student stu)
{
object v = null;
switch (expression)
{
case "id":
v = stu.ID;
break;
case "name":
v = stu.Name;
break;
default:
v = null;
break;
}
return v;
}
}

测试一下好不好使

复制代码 代码如下:

static void Main(string[] args)
{
ListTest<Student> test = new ListTest<Student>();
for (int i = 0; i < 10; i++)
{
Student stu = new Student(i,string.Format("N_"+(9-i)));
test.list.Add(stu);
}
Console.WriteLine("元数据");
for (int i = 0; i < test.list.Count;i++ )
{
Console.WriteLine(string.Format("ID:{0} , Name:{1}", test.list[i].ID, test.list[i].Name));
}

Console.WriteLine("Name 递增");
test.Sort(new StudentComparer("name", true));
for (int i = 0; i < test.list.Count; i++)
{
Console.WriteLine(string.Format("ID:{0} , Name:{1}", test.list[i].ID, test.list[i].Name));
}
}

看看效果

Capture

.NET List的sort如何为我们排序

用ILSpy反编译可以看到在调用List<T>的sort()方法时内部调用的时 this.Sort(0, this.Count, null); 然后往里面扒,经过一系列异常处理后会调用 Array.Sort<T>(this._items, index, count, comparer); this._items是把List内容转换成数组,同样再经历一些列异常处理,调用方法 ArraySortHelPEr<T>.Default.Sort(array, index, length, comparer); 再往里就和我们上面写的方法大同小异了,只不过微软加了很多异常处理和算法优化。

策略模式

看清楚了上面这个例子我们就可以进入正题,说说我们的策略模式了。策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。(原文:The Strategy Pattern defines a family of algorithms,encapsulates each one,and makes them interchangeable. Strategy lets the algorithm VARy independently From clients t@R_126_2570@ use it.)

5366d0160924ab189a9f061935fae6cd7b890b16

这个模式涉及到三个角色:

环境(Context)角色:持有一个Strategy类的引用。抽象策略(Strategy)角色:这是一个抽象角色,通常由一个接口或抽象类实现。此角色给出所有的具体策略类所需的接口。具体策略(concreteStrategy)角色:包装了相关的算法或行为。

相信大家可以分方便的把我们上面例子中的类对应上策略模式的角色,IComparer接口是我们的抽象策略角色, ListTest<T> 类持有抽象策略的引用是环境(在Sort方法中,其实可以把接口定义为类的属性,在构造函数中赋值,不过不适合此场景,毕竟并不是所有List都需要排序,不能强制其接受一个可能会用不到的接口,当然对每个实例都需要用某个策略的场景是合适的),毫无疑问我们实现IComparer抽象策略的类就是具体策略。

使用场景

策略模式很容易理解,不过能够用它很好的理解封装变化和针对接口编程者两个面向对象设计原则,我们来看看什么时候我们会用策略模式

1、 多个类只区别在表现行为不同,可以使用Strategy模式,在运行时动态选择具体要执行的行为。

2、 需要在不同情况下使用不同的策略(算法),这些策略有统一接口。

3、 对客户隐藏具体策略(算法)的实现细节,彼此完全独立。

策略模式的优势和不足

优点:

1、 提供了一种替代继承的方法,而且既保持了继承的优点(代码重用)还比继承更灵活(算法独立,可以任意扩展)。

2、 使用组合,避免程序中使用多重条件转移语句,使系统更灵活,并易于扩展。

3、 遵守大部分GRASP原则和常用设计原则,高内聚、低偶合。

缺点:

1、 因为每个具体策略类都会产生一个新类,所以会增加系统需要维护的类的数量。

脚本宝典总结

以上是脚本宝典为你收集整理的关于.NET Framework中的设计模式--应用策略模式为List排序全部内容,希望文章能够帮你解决关于.NET Framework中的设计模式--应用策略模式为List排序所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。