Encapsulation in the sorting algorithm of the change of encapsulation

Source: Internet
Author: User
Tags abstract define array comparison config implement sort domain
Encapsulation | sorting | The algorithm envisages such a requirement that we need to provide a component for our own framework that is responsible for sorting. At present, we need to implement bubble sort algorithm and fast sorting algorithm, according to the idea of "interface-oriented programming", we can provide a unified interface Isort for these sort algorithms, in this interface there is a method sort (), which can accept an object array parameter. After an array is sorted, it is returned. The interface is defined as follows:

public interface Isort
{
void Sort (ref object[] besorted);
}
Its class diagram is as follows:


In general, however, permutations are ordered in order, such as ascending, or descending, and the results are not the same. The easiest way to do this is to use an if statement, such as in the Quicksort class:

public class Quicksort:isort
{
private string M_sorttype;
Public QuickSort (String sorttype)
{
M_sorttype = SortType;
}
public void Sort (ref object[] besorted)
{
if (M_sorttype.toupper (). Trim () = = "Ascending")
{
Perform a quick sort of ascending order;
}
Else
{
Performs a quick sort in descending order;
}
}
}
Of course, we can also define a string type of SortType as an enumeration type, reducing the likelihood of an error. However, with the careful reading of the code, we can see that the code is very rigid, and once we need to expand it, if we are asked to add a new sort order, such as a dictionary order, then the work we face will be very heavy. In other words, changes have been made. Through analysis, we find that the order of the so-called ordering, is precisely the ranking algorithm is the most important part, it determines who is ranked in the front, who ranked after. However, it does not belong to the sorting algorithm, but rather a comparison strategy, which is said to be a comparison of the behavior.

If you carefully analyze the classes that implement the Isort interface, such as the Quicksort class, it is necessary to compare two objects when implementing the sorting algorithm. In a refactoring approach, essentially we can extract a private method compare () in the Sort method, and determine which object is in front and which object is behind by returning a Boolean value. Obviously, what may change is this comparison behavior, using the principle of "encapsulation abstraction", we should establish a proprietary interface icompare for the behavior, but define class objects that implement ascending, descending, or dictionary sorting respectively.


In each class constructor that implements the Isort interface, we introduce the Icompare interface object to establish the weak coupling relationship between the sorting algorithm and the comparison algorithm (because this relationship is related to the abstract Icompare interface), such as The Quicksort class:

public class Quicksort:isort
{
Private Icompare M_compare;
Public QuickSort (Icompare Compare)
{
M_compare= Compare;
}
public void Sort (ref object[] besorted)
{
Implementation of a slightly
for (int i = 0; I besorted.length-1 i++)
{
if (M_compare.compare (besorted[i],besorted[i+1))
{
Slightly
}
}
Implementation of a slightly
}
}


The final class diagram is as follows:


By encapsulating the comparison strategy to cope with its changes, it is clearly the design of the stategy model. In fact, the sorting algorithm here may also be changing, such as the implementation of two-fork tree sorting. Since we have introduced the idea of "interface-oriented programming", we can easily add a new class Binarytreesort to implement the Isort interface. For callers, the implementation of the Isort interface is also a strategy pattern. The class structure at this time is entirely a state of extended development, and it is fully adaptable to the changes in the new requirements of the class library caller.

Take PetShop as an example, in this project involves the management of orders, such as inserting orders. Given the amount of traffic, PetShop provides a synchronous and asynchronous way to order management. Obviously, only one of these two approaches can be used in practical applications and is determined by the specific application environment. To deal with such a potentially frequent change, we still need to take advantage of the principle of "encapsulation change" to create an abstraction-level object, the Iorderstrategy interface:

public interface Iorderstrategy
{
void Insert (PetShop.Model.OrderInfo order);
}
Then define two classes OrderSynchronous and orderasynchronous. The class structure is as follows:



In PetShop, because users can change the policy of inserting an order at any time, it is not possible to have a coupling relationship with a specific order policy object for the order domain object of the business layer. In other words, in the domain object order class, you cannot new a specific ordering policy object, such as the following code:

Iorderstrategy orderinsertstrategy = new ordersynchronous ();
In Martin Fowler's article, "The IOC container and the dependency injection model," a solution to such problems is proposed, which he calls dependency injection. However, because PetShop does not use IOC containers such as sping.net, the problem of dependency resolution is usually done using a configuration file combined with reflection. This is done in the Realm object order class:

public class Order
{
private static readonly Iorderstategy orderinsertstrategy = Loadinsertstrategy ();
private static Iorderstrategy Loadinsertstrategy ()
{
Look up which strategy to use from config file
String path = configurationmanager.appsettings["orderstrategyassembly"];
String className = configurationmanager.appsettings["OrderStrategyClass"];

Load the appropriate assembly and class
Return (iorderstrategy) assembly.load (path). CreateInstance (ClassName);
}
}
In the configuration file Web.config, configure the following section:

<add key= "orderstrategyassembly" value= "PETSHOP.BLL"
<add key= "OrderStrategyClass" value= "PetShop.BLL.OrderSynchronous"
This is actually a compromise service locator mode. It is a good idea to put the logic of locating and creating dependent objects directly into objects, in the case of PetShop. After all, in this case, there are not too many objects that need to rely on injection. But we can also think of a helpless compromise, and once the logic of this dependency injection increases, causing some trouble for the program, a dedicated lightweight IOC container is needed.

Written here, it seems to have been out of the "package change" theme. But in fact we need to understand that to encapsulate change in an abstract way is to address the need for change, but it can only release the caller's relative coupling to the callee, as long as it involves the creation of specific objects, even if the factory model is introduced, the creation of specific factory objects is still essential. So, for some of these already encapsulated changes, we should also take full advantage of the "dependency injection" approach to completely remove the coupling between the two.

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.