当前位置:网站首页>Interpretation and implementation of proxy mode
Interpretation and implementation of proxy mode
2022-06-13 04:06:00 【Cavewang】
Interpretation and implementation of proxy mode
What is agent mode
agent : Don't do it yourself , Get someone to do it for you .
The proxy pattern : Add new functions on the basis of an original function .
classification : Static agents and dynamic agents .
Static proxy
The proxy class is written by the programmer ( The proxy class enhances specific methods of the target object )
Basic steps
1、 Design interfaces : Both the proxy object and the target object implement the same function .
2、 Write the target object ( class ): Implementation interface
3、 Write proxy objects ( class ): Implementation interface , Inject the target object , Call its methods , Finally, the enhancement method .
Realization
Original way : Core business and service methods are written together
public class TeamService {
public void add(){
try {
System.out.println(" Start business ");
System.out.println("TeamService---- add----");// The core business
System.out.println(" Commit transaction ");
} catch (Exception e) {
e.printStackTrace();
System.out.println(" Roll back the transaction ");
}
}
}
Proxy mode to achieve :
/** * section : Service code , Cut into the core code , Cut into where , Given four positions */
public interface AOP {
void before();
void after();
void exception();
void myFinally();
}
public class TranAOP implements AOP {
@Override
public void before() {
System.out.println(" Business ----before");
}
@Override
public void after() {
System.out.println(" Business ----after");
}
@Override
public void exception() {
System.out.println(" Business ----exception");
}
@Override
public void myFinally() {
System.out.println(" Business ----myFinally");
}
}
public class LogAop implements AOP{
@Override
public void before() {
System.out.println(" journal ----before");
}
@Override
public void after() {
System.out.println(" journal ----after");
}
@Override
public void exception() {
System.out.println(" journal ----exception");
}
@Override
public void myFinally() {
System.out.println(" journal ----myFinally");
}
}
public class ProxyAOPService implements IService {
private IService service;// Proxied object
private AOP aop;// To add cut
public ProxyAOPService(IService service, AOP aop) {
this.service = service;
this.aop = aop;
}
@Override
public void add() {
try {
aop.before();
service.add();// The proxy object works
aop.after();
}catch (Exception e){
aop.exception();
}finally {
aop.myFinally();
}
}
}
@Test
public void test02(){
IService teamService=new TeamService();// Proxied object -- Core content
AOP logAop=new LogAop();// section - service content
AOP tranAop=new TranAOP();
IService service=new ProxyAOPService(teamService,logAop); // Proxy object -- First class agent
IService service2=new ProxyAOPService(service,tranAop);// Proxy object -- Secondary agent
service2.add();
}
summary
1) It can be done without modifying the function of the target object , Expand the function of the target object .
2) shortcoming :
Because the proxy object , You need to implement the same interface as the target object . So there will be a lot of proxy classes , Too many classes .
Once the interface has added methods , Target object and proxy object should be maintained .
Every time you write a target class , All need to be rewritten ( At least ) A proxy class , It's too troublesome , Therefore, we hope that the system can automatically generate proxy objects , Dynamic proxy .
A dynamic proxy
Static proxy : The proxy class must exist ,
A dynamic proxy : While the program is running , Dynamically generate proxy classes according to the objects to be represented .
type :
1、 be based on JDK Dynamic proxy for
2、 be based on CGLIB Dynamic proxy for
be based on JDK Dynamic proxy for
public class ProxyFactory {
private IService service;// Target audience
private AOP aop;// section
public ProxyFactory(IService service, AOP aop) {
this.service = service;
this.aop = aop;
}
/** * Get an example of a dynamic proxy * @return */
public Object getProxyInstance() {
return Proxy.newProxyInstance(
service.getClass().getClassLoader(),
service.getClass().getInterfaces(),
new InvocationHandler() {
// Callback function Write proxy rules
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
aop.before();
Object invoke = method.invoke(service, args);// The core business
aop.after();
return invoke;
}catch (Exception e){
aop.exception();
e.printStackTrace();
throw e;
}finally {
aop.myFinally();
}
}
}
);
}
}
public static void main(String[] args) {
// Target audience -- Proxied object
TeamService teamService=new TeamService();
// section
AOP tranAop=new TranAOP();
AOP logAop=new LogAop();
// Get proxy object
IService service= (IService) new ProxyFactory(teamService,tranAop).getProxyInstance();
IService service1= (IService) new ProxyFactory(service,logAop).getProxyInstance();
service1.add();// The core business + A complete business method with service code mixed together
}
Proxy objects do not need to implement interfaces , But the target object must implement the interface ; Otherwise, it can't be used JDK A dynamic proxy
If you want to expand the function , But the target object doesn't implement the interface , How to expand functions ?
Subclass to implement the proxy CGLIB.
be based on CGLIB Dynamic proxy for
Cglib agent , Also called subclass proxy . Build a subclass object in memory to extend the function of the target object .
- JDK There is a limitation to dynamic proxies , That is, objects using dynamic proxies must implement one or more interfaces . If The proxy class does not want to implement the interface , You can use CGLIB Realization .
- CGLIB Is a powerful high-performance code generation package , It can be extended during runtime Java Class and Implementation Java Interface . It is widely used by many AOP The framework uses , for example Spring AOP and dynaop, To provide them with a method of interception.
- CGLIB The bottom layer of the package is through the use of a small and fast bytecode processing framework ASM, To transform the bytecode and generate a new class . Direct use of ASM, Because it requires you to be right JVM The internal structure includes class The file format and instruction set are familiar .
Core method functions
Enhancer: Core class , Provide subclass objects of the target object ( Proxy object )
create(): Provide proxy objects
MethodInterceptor: Interface
intercept: Abstract method , Enhancements to target object methods
public class CglibProxyFactory {
// Target audience
private NBAService nbaService;// Without implementing the interface
// section
private AOP aop;// section
/** * Create proxy object * @param nbaService * @param aop * @return */
public Object getProxyInstance(NBAService nbaService,AOP aop){
return Enhancer.create(nbaService.getClass(),
new MethodInterceptor() {
@Override
public Object intercept(Object o, Method method, Object[]
objects, MethodProxy methodProxy) throws Throwable {
try {
aop.before();
Object o1 = methodProxy.invokeSuper(o, objects);
aop.after();
return o1;
}catch (Exception e){
aop.exception();
throw e;
} finally {
System.out.println("finally-----------");
}
}
});
}
}
public static void main(String[] args) {
// Target audience : No interface
NBAService nbaService=new NBAService();
// Create facets
AOP tranAop=new TranAOP();
// Create proxy object : choice cglib A dynamic proxy
NBAService proxyInstance = (NBAService) new CglibProxyFactory().getProxyInstance(nbaService, tranAop);
int res=proxyInstance.add("huren",1001);
System.out.println(res);
}
边栏推荐
- Single chip microcomputer: a/d differential input signal
- 环评图件制作-数据处理+图件制作
- 干预分析 + 伪回归
- 单片机:EEPROM 多字节读写操作时序
- Interpretation of mobile phone private charging protocol
- SCM: introduction and operation of EEPROM
- [test development] use case
- Data analysis report
- [notes] summarize common horizontal and vertical centering methods
- Principle, composition and functions of sensors of Dajiang UAV flight control system
猜你喜欢
Unity shader learning 004 shader debugging platform difference third-party debugging tools
MCU: NEC protocol infrared remote controller
干预分析 + 伪回归
史上最详细的Swin-Transformer 掩码机制(mask of window attentation)————shaoshuai
Use ASE encryption and decryption cache encapsulation in Vue project
Sword finger offer II 022 Entry node of a link in a linked list
Advanced Mathematics (Seventh Edition) Tongji University exercises 1-3 personal solutions
Single chip microcomputer: MODBUS multi computer communication program design
Translation of ego planner papers
[web] cookies and sessions
随机推荐
R: Employee turnover forecast practice
单片机:PCF8591硬件接口
SQL 进阶挑战(1 - 5)
MCU: pcf8591 hardware interface
Real time requirements for 5g China Unicom repeater network management protocol
单片机:PCF8591 应用程序
Difference between OKR and KPI
[test development] use case
单片机:A/D 和 D/A 的基本概念
Lambda end operation find and match findfirst
单片机:A/D(模数转换)的主要指标
[kubernetes series] pod chapter actual operation
Lambda end operation count
EIA map making - data processing + map making
单片机:I2C通信协议讲解
1-72 convert string to decimal integer
Forgotten fleeting years
Advanced Mathematics (Seventh Edition) Tongji University exercises 1-3 personal solutions
单片机信号发生器程序
2022春学期总结