Java static proxy dynamic proxy in depth study

  • 2020-04-01 01:09:18
  • OfStack

I. agency mode
The proxy pattern is a common Java design pattern, characterized by the same interface between the proxy class and the delegate class. The proxy class is mainly responsible for preprocessing messages, filtering messages, forwarding messages to the delegate class, and post-processing messages for the delegate class.
There is usually an association between the proxy class and the delegate class. The object of a proxy class is associated with the object of a delegate class. The object of the proxy class does not really implement the service itself, but provides a specific service by calling the relevant methods of the object of the delegate class.
According to the creation time of the proxy, the proxy class can be divided into two types:
Static proxy: the source code is automatically generated and compiled by the programmer or by a particular tool. The.class file for the proxy class already exists before the program runs.
Dynamic proxy: created dynamically while the program is running using reflection.
A single static proxy

 
public interface CountDao 
{ 
//View 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 account method...
Tranc end
Multiple static agents
Added to the above code
 
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 calling code becomes
 
//Embodies the idea of aggregation, the combination between agents
public static void main(String[] args) 
{ 
CountTrancProxy trancProxy = new CountTrancProxy(new CountDaoImpl()); 
CountLogProxy logPro = new CountLogProxy(trancProxy); 
logPro.queryCount(); 
} 

Log the start
Before the transaction
View account method...
After the transaction
The Log end
Four,
In fact, proxy classes can be used to achieve the effect of proxy through inheritance or interface implementation. However, when multiple proxy classes need to be combined with each other, inheritance is not flexible, and proxy classes need to be constantly rewritten, while the way to implement interface is very easy to achieve the combination of proxy classes through aggregation.


Related articles: