Design Pattern in. NET Framework -- Application policy pattern is sorted by list

Source: Internet
Author: User
ArticleDirectory
    • Simple sort
    • Compile a general list <t> sorting method
    • How to sort the sort of. Net list
    • Rule Mode
    • Use Cases
    • Advantages and disadvantages of the Rule Mode
    • Reference
Simple sort

Sorting is common during programming. net is the most common sorting of the generic list <t>. If T is a simple sorting of data types, you can directly call the sort () method of the list, but what if the objects to be sorted are complicated? We know that list <t> sort () is implemented by fast sorting and fast sorting, you need to know the comparison results between items in the list. If it is a simple int type, you can directly judge it. For objects that implement the icomparable interface, you can call its compareto () compare the size of items. The following is a quick sorting method.

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

 

 

 

Problem

The first two cases can be sorted, but we cannot require all objects to be sorted to implement the icomparable interface. Even if each object can implement the icomparable interface, if you want to sort multiple fields in an object, such as a student object, you sometimes want to sort by name, sometimes by score, or sometimes by age, how can this problem be solved?

According to the object-oriented thinking, we need to separate the changes and encapsulate the changes. What changes occur when we sort the list <t> is how to compare the sizes of the two objects.AlgorithmIf we can take this algorithm out, sorting will be much simpler. No matter what sort, the algorithm is from. What we want to encapsulate is how to compare the size of two items, to achieve scalability, we need to follow another important principle of object-oriented design, for interface programming, rather than for implementation programming.

Compile a general list <t> sorting method

First, define an interface, which contains a method to compare the item size. It is passed in as a parameter during sorting, and of course its implementation class. With this idea, we can write a list <t> sorting method by ourselves.

 
Public InterfaceIcomparer_sly <t>
 
{IntCompare (t x, t y );}

 

 

Then, in order to test, we add a package for the list <t> and write our own sort method, which is also implemented by fast sorting internally. We are always confused about our change part-compare the size algorithm, and we will block it and pass it as a parameter

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

For example, we now have a student entity.

 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 you want to sort the list <t> composed of this object, you only need a class studentcomparer that implements icomparer_sly <student> and internally implements the compare () method for comparing the size of the object (), at the same time, we can add the increment or decrease sort control.

 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 ;}  //  The system method is not implemented by yourself. In fact, it is difficult to implement it by yourself to compare the data sizes of two identical 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 to enable

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

View results

 

 

How to sort the sort of. Net list

Using ilspy decompilation, you can see this. sort (0, this. count, null); and then dig into it, after a series of exception processing will call array. sort <t> (this. _ items, index, Count, comparer); this. _ items converts the list content to an array. It also goes through some column Exception Processing and calls the arraysorthelper method. <t>. default. sort (array, index, length, comparer); it is similar to the method we wrote above, but Microsoft adds a lot of Exception Processing and algorithm optimization.

Rule Mode

After reading the above example, we can start to discuss our policy model. Policy patterns define a series of algorithms, encapsulate each algorithm, and make them replaceable. The rule mode allows algorithms to change independently of customers who use it. (Original article: 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 mode involves three roles:

    • Context Role: Hold 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 provides all the interfaces required for specific policy classes.
    • Concretestrategy: encapsulates related algorithms or actions.

I believe that you can easily map the class in the above example to the role in the policy mode. The icomparer interface is our abstract policy role, listtest <t>The class holds an abstract policy reference as an environment (in the sort method, you can actually define an interface as a Class Attribute and assign a value to the constructor, but it is not suitable for this scenario, after all, not all lists need to be sorted and cannot be forced to accept an interface that may not be used. Of course, it is appropriate for each instance to use a certain policy ), undoubtedly, the class that implements the icomparer abstract policy is the specific policy.

Use Cases

The rule mode is easy to understand, but we can use it to better understand the encapsulation changes and the object-oriented design principles for interface programmers. Let's take a look at when we will use the policy mode.

1. Multiple classes only differ in performance behavior. You can use the Strategy Mode to dynamically select the behavior to be executed during running.

2. Different policies (algorithms) must be used in different situations. These policies have unified interfaces.

3. Hiding implementation details of specific policies (algorithms) from customers is completely independent of each other.

Advantages and disadvantages of the Rule Mode

Advantages:

1. provides a method to replace inheritance, and maintains the advantages of inheritance (CodeReuse) is more flexible than inheritance (algorithms are independent and can be expanded at will ).

2. Use combinations to avoidProgramTo make the system more flexible and easy to expand.

3. comply with most grasp principles and common design principles, with high cohesion and low coupling.

Disadvantages:

1. Because each specific policy class generates a new class, the number of classes to be maintained by the system is increased.

Reference

1. http://baike.baidu.com/view/2141079.htm

2. http://www.cnblogs.com/zhenyulu/articles/82017.html

3. Head first design mode

I hope this series can be used to inspire myself by writing a directory, and also facilitate searching for the design patterns in. NET Framework.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.