I. Proxy Mode
The proxy mode is a common java design mode. It features that the proxy class has the same interface as the delegate class. The proxy class is mainly responsible for preprocessing, filtering, and forwarding messages to the delegate class, and post-processing messages.
There is usually an association between the proxy class and the delegate class. A proxy class object is associated with a delegate class object. The proxy class object itself does not actually implement the service, but calls the relevant methods of the delegate class object, to provide specific services.
According to the agent creation period, the agent class can be divided into two types:
Static Proxy: the source code is automatically generated by the programmer or a specific tool before compilation. The. class file of the proxy class already exists before the program runs.
Dynamic Proxy: dynamically created using the reflection mechanism when running the program.
2. Single Static proxy
Copy codeThe Code is as follows: public interface CountDao
{
// View the account Method
Public void queryCount ();
}
Public class CountDaoImpl implements CountDao
{
Public void queryCount ()
{
System. out. println ("view account method ...");
}
}
Public class CountTrancProxy implements CountDao
{
Private CountDao countDao;
Public CountProxy (CountDao countDao)
{
This. countDao = countDao;
}
@ Override
Public void queryCount ()
{
System. out. println ("tranc start ");
CountDao. queryCount ();
System. out. println ("tranc end ");
}
}
Public class TestCount
{
Public static void main (String [] args)
{
CountTrancProxy countProxy = new CountTrancProxy (new CountDaoImpl ());
CountProxy. updateCount ();
}
}
Tranc start
View the account method...
Tranc end
3. Multiple Static proxies
AddedCopy codeThe Code is as follows: public class CountLogProxy implements CountDao
{
Private CountDao countDao;
Public CountLogProxy (CountDao countDao)
{
This. countDao = countDao;
}
@ Override
Public void queryCount ()
{
System. out. println ("Log start ");
CountDao. queryCount ();
System. out. println ("Log end ");
}
}
The call code becomesCopy codeThe Code is as follows: // embodies the idea of aggregation and the combination of agents.
Public static void main (String [] args)
{
CountTrancProxy trancProxy = new CountTrancProxy (new CountDaoImpl ());
CountLogProxy logPro = new CountLogProxy (trancProxy );
LogPro. queryCount ();
}
Log start
Before Transaction Processing
View the account method...
After the transaction is processed
Log end
Iv. Summary
In fact, the proxy class can be used to achieve the proxy effect through inheritance or interface implementation. However, when multiple proxy classes need to be combined, inheritance is not flexible and the proxy class needs to be constantly rewritten, the method of implementing interfaces is very easy to implement the combination between proxy classes through aggregation.