Synchronization and Asynchronization are completely two different forms. Because different calling methods lead to different programming languages and different writing methods, the design of the entire software framework is naturally affected. A feasible method is provided here to transform the software without affecting the framework.
This is the background of the problem. In the past, the development was conducted in synchronous mode. The business layer logic was unified in a class, such as cbiz, and a cmodemsyn class was aggregated, among them, the modem class is a core function class that provides some modem-related operations (synchronous mode). In this way, in the cbiz class, the modem class is called mainly, and do some corresponding business processing, such as sending socket notifications. The approximate program framework code is as follows:
Cbiz: Recv ()
{
Playvoice (); // 1
Bool flag = _ MODEM. Recv (); // 2
If (FLAG)
{
Showindialog (); // 2
Sendsocket (); // 3
}
Else
{
Writelog (); // 4
}
}
Among them, 1, 2, 3, 4 are some methods of cbiz itself, which is also very simple, if successful, the data is displayed and the socket is sent, and if it fails, the log is recorded.
Its structure is as follows:
Now the problem is coming. The modem class has changed from synchronous to asynchronous cmodemasyn:
Cmodemasyn: Recv ()
{
Kernel_call (..., Asyn); // asynchronous call
}
Cmodemasyn: Wait ()
{
Status = waitforevent ();
Switch (Status)
Case CONNECT:
Case transmit_begin:
Case transmit_over:
}
That is to say, in asynchronous mode, the modem class cannot provide a synchronous Recv Method for calling at the logic layer. When the modem class is sent, only the class itself knows. In this case, for processing, it must be passed in a callback method in the modem class. For example, according to the above cbiz logic, the socket must be sent simultaneously on the UI, that is, the following situation:
Cmodemasyn: Wait ()
{
Waitforevent ();
Switch (Status)
..
..
Case transmit_over:
Showindialog (); // 5
Sendsocket (); // 6
}
However, if such a statement is used, the modem class is associated with the logic of the business layer to implement functions unrelated to itself. Such extensibility is not good. Here, we need an interface:
Imodemevent
{
Virtual void onconnect () = 0;
Virtual void ontransmit () = 0;
}
To isolate the business layer from the event interface, we design another adapter.
Class cmodemeventadapter: Public imodemevent
{
Public:
Void Init (cbiz * biz) {_ biz = biz ;}
Void onconnect () {_ biz-> sendsocket ();}
Void ontransmit (_ biz-> writelog ();)
};
In this way, we have implemented a relatively complete and good OO design, and implemented the transformation from synchronous to asynchronous without affecting the existing ones.