Requirement: automatically construct the corresponding request based on the input action parameter.
Go directlyCode.
First define a myrequest class. Sub-classes include addrequest, loadrequest, and deleterequest.
Myrequest
1 Public Class Myrequest
2 {
3 Public String Action { Get ; Private Set ;}
4 // Public gridpagerparams pager {Get; private set ;}
5
6 Public Myrequest ()
7 {
8
9 }
10 Public Virtual String MSG ()
11 {
12 Return Action. tostring ();
13 }
14 }
Myrequest defines a virtual method MSG ();
Each subclassAlgorithmDifferent, You can override this method.
The following is the key: myrequestcreator
Myrequestcreator is responsible for determining the parameter action and returning the corresponding request.
Myrequestcreator
Public Class Myrequestcreator
{
Private Static Dictionary < String , Myrequestcreator. _ newmytype > _ Creatordict = New Dictionary < String , Myrequestcreator. _ newmytype > ();
Private Delegate Myrequest _ newmytype ();
Static Myrequestcreator () // Initialization
{
_ Creatordict. Add ( " Load " , New Myrequestcreator. _ newmytype ( Delegate (){ Return New Loadrequest ();}));
_ Creatordict. Add ( " Add " , New Myrequestcreator. _ newmytype ( Delegate (){ Return New Addrequest ();})); //
_ Creatordict. Add ( " Delete " , New Myrequestcreator. _ newmytype ( Delegate (){ Return New Myrequest ();}));
}
Public Static Myrequest createhandler ( String Action)
{
If (_ Creatordict. containskey (Action ))
{
Myrequest rethandler = _ Creatordict [action]. Invoke ();
Try
{
Return Rethandler;
}
Catch (Exception E)
{
Throw New Exception ( " Request Processing failed! " , E );
}
}
Return Null ;
}
}
Client call time:
Myrequest request = myrequestcreator. createhandler ("LOAD ");
In this way, you can generate a specific subclass of myrequest and use its function in myrequest mode.
There is no if or case in the whole process. In combination with emit, you can also dynamically Add a subclass of myrequest and register it in myrequestcreator.
More importantly, using this method is much faster than generating an object based on activator. createinstance (typeof (myrequest);, which is close to directly using new object.