当前位置:网站首页>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);
}
边栏推荐
- Unity Shader 学习 004-Shader 调试 平台差异性 第三方调试工具
- ROS话题与节点
- Discussion sur la modélisation de la série 143
- Single chip microcomputer: main index of a/d (analog-to-digital conversion)
- 1.4.2 Capital Market Theroy
- Translation of ego planner papers
- Goframe day 5
- [test development] installation of test management tool Zen path
- 单片机串口通信原理和控制程序
- Redis数据持久化
猜你喜欢

MCU: pcf8591 hardware interface

环评图件制作-数据处理+图件制作
![[zeloengine] localization process /imgui Chinese culture](/img/ec/7eb7edc236b09994c2981e6f13dc68.png)
[zeloengine] localization process /imgui Chinese culture

1.4.2 Capital Market Theroy

单片机:红外遥控通信原理

高等数学(第七版)同济大学 习题1-3 个人解答

5G China unicom 直放站 网管协议 实时性要求

Lightweight digital mall system based on PHP
![[notes] summarize common horizontal and vertical centering methods](/img/0a/9625e7e459be69a2a8d4e016a20f4d.jpg)
[notes] summarize common horizontal and vertical centering methods

USB-IF BC1.2充电协议解读
随机推荐
[note]vs2015 compilation of masm32 using MASM32 Library
Binocular vision -- creating an "optimal solution" for outdoor obstacle avoidance
单片机:A/D 和 D/A 的基本概念
Precautions for stream flow
Real time requirements for 5g China Unicom repeater network management protocol
Modeling discussion series 143 data processing, analysis and decision system development
EIA map making - data processing + map making
leetcode.1 --- 两数之和
Advanced Mathematics (Seventh Edition) Tongji University exercises 1-3 personal solutions
Use ASE encryption and decryption cache encapsulation in Vue project
OKR和KPI的区别
Common array methods in JS (map, filter, foreach, reduce)
The WebView case of flutter
5G China unicom AP:B SMS ASCII 转码要求
[zeloengine] localization process /imgui Chinese culture
[notes] summarize common horizontal and vertical centering methods
Hugo 博客搭建教程
双目视觉——打造室外避障的“最优解”
Configuration and practice of shardingsphere JDBC sub database separation of read and write
Lambda termination operation find and match nonematch