My practical design patterns about policy-based Design

Source: Internet
Author: User

BelowArticleThe policy-based design concept is not a classic strategy model.

 

The strategy model is one of the most widely used models. I have been using this pattern for design before I learned the design pattern systematically. I would like to introduce this mode from an example. Assume that there is a PDA ordering system, the frontend is Windows Mobile, and the backend is a web service. The waiter's pda can perform the following three operations: 1. log on to the system using the user name and password. 2. Help customers order orders. 3. Check out the meal. The front end does not contain business logic, but only sends requests to the backend through WebService. The background is responsible for receiving, processing requests, and responding to the processing results. Frontend and backend communication can be performed through WebService, remoting, WCF, or even socket. However, this is not the content discussed in this article. This article focuses on backend communication design. The most intuitive and simple design is to use a function to process a request. The implementation is as follows:

Public   Enum Requesttype
{
Login,
Order,
Payment
}

Public   Bool Processrequest (requesttype type, dataset DS)
{
Switch (Type)
{
Case Requesttype. login:
Return Processlogin (DS );
Break ;
Case Requesttype. Order:
Return Processorder (DS );
Break ;
Case Requesttype. payment:
Return Processpayment (DS );
Break ;
}
}

However, let's hear about this section.CodeIf you want to increase request processing, you need to add a case statement. Therefore, we use the Strategy Mode for refactoring. Before specific application, let's briefly introduce the general implementation of the Strategy Mode.

 

Strategy definesAlgorithmAll sub-classes must implement this interface. context is responsible for managing and managing various strategies. The client does not need to care about the specific algorithm implementation of strategy and its sub-classes, but simply submits the request to the context for processing.

In our scenario, the reality of the stragtegy mode is as follows:


Public   Enum Requesttype
{
Login,
Order,
Payment
}

Public InterfaceRequesthandler
{
BoolProcessrequest (Dataset DS );
}

Public   Class Loginhandler: requesthandler
{
Public   Bool Processrequest (Dataset DS)
{
// Longin TO THE SYSTEM
Return   True ;
}

}

Public   Class Orderhandler: requesthandler
{
Public   Bool Processrequest (Dataset DS)
{
// Make an order
Return   True ;
}

}

Public   Class Paymenthandler: requesthandler
{
Public   Bool Processrequest (Dataset DS)
{
// Make a payment
Return   True ;
}

}

Public sealed class requestmanager
{< br> private dictionary requesttype, requesthandler > handlers;

PublicRequestmanager ()
{
Handlers= NewDictionary<Requesttype, requesthandler>();

// It can use factory pattern here.
Handlers [requesttype. Login] =   New Loginhandler ();
Handlers [requesttype. Order] =   New Orderhandler ();
Handlers [requesttype. Payment] =   New Paymenthandler ();
}

Public   Bool Process (requesttype type, dataset DS)
{
If (Handlers. containskey (type ))
{
Return Handlers [type]. processrequest (DS );
}
Return   False ;
}
}

 

In the definition of the Strategy Mode, the Strategy abstract class defines the algorithm interface to be implemented. In my opinion, the application scope is not only an algorithm, but such an interface can be defined as long as there are common operations, the purpose of defining this interface is to create a contract. sub-classes must implement this interface, that is, they must enforce this contract. In our case, requesthandler is the parent class of strategy, which can be defined as interface or abstract class, depending on whether requesthandler has the common logic of sub-classes, if there is a common logic, it is defined as abstract class, and the common logic is encapsulated into the protected member. If not, it is defined as interface. Loginhandler, orderhandler, and paymenthandler are subclasses of requesthandler. They must implement the processrequest method. Requestmanager is the management class of handlers. It manages the ing relationship between request types and processing classes. The client only needs to call the process of requestmanager for processing and does not care about the specific processing classes. Strategy is very suitable for compiling the framework. The framework sets out the president's processing process. The specific transaction process implements specific processing classes according to the interface. For example, if the system expands and requires that each transaction needs to operate the database, Write File logs, and listen for three steps, three processing interfaces can be defined, each processing class must implement corresponding interfaces to meet the overall process.

Operatedb, log, and audit interfaces must be implemented when transaction request processing classes are added. In this way, the framework and specific business processes are separated.

The Strategy Mode is widely used. It is not only used for request processing, but can be used for scenarios with common input and output and processing using different processing algorithms, the common input and output can be the same parent class as the input or output. For example, the following is an alarm processing engine in the network monitoring system ), input is the source data collected from the network, and output is the corresponding alarm object.

Public   Enum Networkequimenttype
{
Router,
Switch
}

// Input
Public   Abstract   Class Rawdata
{
Public Networkequimenttype type { Get ; Set ;}
Public   String Data { Get ; Set ;}
}

Public class routerdata: rawdata
{< br> /// specific properties
Public string routername { Get ; set ;}
}

Public ClassSwitchdata: rawdata
{
//Specific Properties
Public StringSwitchname {Get;Set;}
}

// Output
Public   Class Alarm
{
Public   Int Level { Get ; Set ;}
Public   Int Type { Get ; Set ;}
}

Public class routeralarm: alarm
{< br> /// specific properties
Public string routername { Get ; set ;}
}

Public class switchalarm: alarm
{< br> /// specific properties
Public string switchname { Get ; set ;}
}

//Strategy
Public InterfaceAlarmhandler
{
Alarm analyserowdata (rawdata rd );
}

Public   Class Routeralarmhandler: alarmhandler
{
Public Alarm analyserowdata (rawdata rd)
{
Routerdata = Rd As Routerdata;
Routeralarm Ra =   New Routeralarm ();
Return RA;
}

}

Public   Class Switchalarmhandler: alarmhandler
{
Public Alarm analyserowdata (rawdata rd)
{
Switchdata = Rd As Switchdata;
Switchalarm SA =   New Switchalarm ();
Return SA;
}
}

 

Strategy is widely used. In the pure C world, you can use table-driven to implement strategy. In the C ++ world, you can use pure OO to implement it, you can also use a template to implement the so-called policy-based design, which is the basis of the Loki library.

Jake's blog in blog Park-simplified development of wireless life

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.