In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces. NET Framework application strategy model for List ranking, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
Simple type sorting
However, the most common thing to use .net is to sort a generic List, which is very simple if T is a simple data type.
The copy code is as follows:
Public List SortSimpleList (List list)
{
List.Sort ()
Return list
}
The same is true for sorting simple types such as string. What if the object we want to sort becomes more complex? we know that List sort () is finally implemented by quick sorting. No matter what sort it is, you need to know the comparison results between item in list. If it is a simple int type, you can directly judge the object that implements the IComparable interface. You can call its CompareTo () to compare the size of the item. Here is a quick sort of writing
The copy code is as follows:
Void Sort (T [] array, int left, int right, IComparer_sly 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)
}
}
problem
For the first two cases, sorting can be achieved, but it is impossible to require all the objects to be sorted to implement the IComparable interface. Even if we can ensure that each object implements the IComparable interface, if you want to sort multiple fields in the object, such as the Student object, sometimes you want to sort by name, sometimes by grade, sometimes by age.
According to the object-oriented idea, to separate the changes and encapsulate the changes, the algorithm that changes when we sort the List is actually how to compare the size of the two objects. If we can come up with this algorithm, the sorting will be much simpler. No matter what sort the algorithm is, the algorithm we want to encapsulate is how to compare the size of the two item. In order to achieve extensibility, we need to follow another important principle of object-oriented design, programming for interfaces, not for implementation.
Write a general List sorting method
First of all, define an interface, in which there is a method to compare the size of item, which is passed as a parameter when sorting, and, of course, its implementation class. With this idea, we can write a sorting method of List ourselves.
The copy code is as follows:
Public interface mparer_sly {
Int Compare (T x, T y)
}
Then for testing, we add a wrapper to List and write our own Sort method, which is also implemented internally in quick sorting. We have been puzzling our change part-- comparing the size algorithm, and we seal it up and pass it as a parameter.
The copy code is as follows:
Using System
Using System.Collections.Generic
Namespace Test.Stategy
{public class ListTest
{
Public List list = new List ()
Public void Sort (IComparer_sly comparer)
{
T [] array = list.ToArray ()
Int left = 0
Int right = array.Length-1
QuickSort (array, left, right, comparer)
List = new List (array)
}
Private void QuickSort (S [] array, int left, int right, IComparer_sly 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)
}
}
}
}
For example, now we have an entity of Student.
The copy code is as follows:
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;}
}
If we want to sort the List made up of this entity, we only need a class StudentComparer that implements IComparer_sly and internally implements its comparison method-Compare (), and we can add control over whether to increase or decrease the sort.
The copy code is as follows:
Class StudentComparer: IComparer_sly
{
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
}
/ / here I am lazy to call the system method, which is not implemented by myself. In fact, it is more troublesome to compare the data size of two arbitrary similar types.
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
}
}
Test whether it works.
The copy code is as follows:
Static void Main (string [] args)
{
ListTest test = new ListTest ()
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)); } } 看看效果How does the sort of .NET List sort for us?
With ILSpy decompilation, you can see that this.Sort (0, this.Count, null) is called internally when the sort () method of List is called; then, after a series of exception handling, Array.Sort (this._items, index, count, comparer) will be called; this._items converts the List content into an array, and also goes through some series of exception handling, calling the method ArraySortHelper.Default.Sort (array, index, length, comparer) Further on, it is more or less the same as what we wrote above, except that Microsoft has added a lot of exception handling and algorithm optimization.
Strategy mode
After taking a clear look at the above example, we can get to the point and talk about our strategic model. The policy pattern defines a series of algorithms, encapsulates each algorithm, and makes them interchangeable. The policy pattern allows the algorithm to change independently of the customers who use it. (original: 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.)
This model involves three roles:
Context role: holds a reference to the Strategy class. Abstract Policy (Strategy) role: this is an abstract role, usually implemented by an interface or abstract class. This role gives the required interfaces for all specific policy classes. Specific strategy (ConcreteStrategy) role: wraps the relevant algorithm or behavior.
I believe you can easily correspond the class in our example above to the role of the policy pattern. The IComparer interface is our abstract policy role, and the ListTest class holds the abstract policy reference as the environment. (in the Sort method, you can actually define the interface as a class property and assign a value in the constructor, but it is not suitable for this scenario. After all, not all List need to be sorted and cannot be forced to accept an interface that may not be used. Of course, it is appropriate for scenarios where each instance needs to use a policy), there is no doubt that the class that implements the IComparer abstract policy is the concrete policy.
Working with scen
The policy pattern is easy to understand, but we can use it to understand the two object-oriented design principles of encapsulating changes and targeting interface programmers. Let's see when we will use the policy pattern.
1. Multiple classes only show different behaviors. You can use Strategy mode to dynamically select the specific behavior to be executed at run time.
2. Different policies (algorithms) need to be used in different situations, and these policies have a unified interface.
3. Hide the implementation details of specific strategies (algorithms) from customers, which are completely independent of each other.
Advantages and disadvantages of strategy model
Advantages:
1. It provides a method to replace inheritance, and it not only maintains the advantages of inheritance (code reuse), but also is more flexible than inheritance (algorithm independent, can be extended arbitrarily).
2. Use combination to avoid the use of multiple conditional transfer statements in the program, making the system more flexible and easy to expand.
3. Abide by most of the GRASP principles and common design principles, high cohesion and low coupling.
Disadvantages:
1. Because each specific policy class produces a new class, it increases the number of classes that the system needs to maintain.
Thank you for reading this article carefully. I hope the article "how to sort List in .NET Framework" shared by the editor will be helpful to you. At the same time, I hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.