Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to enhance the function of a class in Java

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

Java how to enhance the function of a class, I believe that many inexperienced people do not know what to do, so this paper summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.

First of all, write the function to be added directly in the method, which is the least recommended, because it violates the java code's principle of "open to extension, closed to modification", affects the use of previous code, and is very troublesome to maintain later.

Second, using inheritance, provide a class to inherit the current class, rewrite the method to be enhanced, you can add or enhance the function, the way of inheritance does not affect the use of the original class, and the code implementation is simple, but can only enhance the function of one class, not batch enhance the function of a class of things. If multiple classes want to modify functionality at the same time, you have to write a lot of subclasses, which will result in code redundancy and is not conducive to later maintenance.

Third, using the decorator pattern, for example, there is a Singer class that implements the Sing interface, and now you want to enhance the sing method of the Singer class, as follows:

Public interface SingAble {

Public void sing ()

}

Public class Singer implements SingAble {

@ Override

Public void sing () {

System.out.println ("the original sing!")

}

}

Public class Decorator implements SingAble {

Private SingAble singer

Public Decorator (SingAble singer) {

This.singer = singer

}

@ Override

Public void sing () {

System.out.println ("before sing...")

Singer.sing ()

System.out.println ("after sing...")

}

}

Public class DecoratorTest {

Public static void main (String [] args) {

SingAble singer = new Singer ()

SingAble obj = new Decorator (singer)

Obj.sing ()

}

}

Output:

Before sing...

Sing a song...

After sing...

The decorator pattern can dynamically enhance the function of a class of things, and can be dynamically undone, while the inherited function is static and can not be dynamically added or deleted.

Fifth, use the proxy mode, the code is as follows:

Public interface SingAble {

Public void sing ()

}

Public class Singer implements SIngAble {

@ Override

Public void sing () {

System.out.println ("sing a song...")

}

}

Public class Proxy implements SingAble {

Private SingAble singer

Public Proxy () {

This.singer = new Singer ()

}

@ Override

Public void sing () {

Before ()

Singer.sing ()

Atfer ()

}

Private void before () {

System.out.println ("before sing...")

}

Private void atfer () {

System.out.println ("after sing...")

}

}

Public class ProxyTest {

Public static void main (String [] args) {

SingAble singer = new Proxy ()

Singer.sing ()

}

}

Output:

Before sing...

Sing a song...

After sing...

The proxy mode looks very similar to the decorator mode, but in fact, there is a difference. The decorator mode extends the function of the object in a transparent way to the client, which is an alternative to the inheritance relationship, and its emphasis is on enhancing the function for the decorative object. However, the proxy mode is more inclined to control access to the object. A proxy class is like an intermediary that can hide specific information about an object from its customers. When using the proxy pattern, an instance of an object is created directly in the proxy class, so the relationship between the proxy class and the real object is determined at compile time. When using decorator mode, the original object is usually passed in as a parameter.

The agent mode can also increase the function of a class of things in batches, and the division of the function is clearer, which is convenient for later maintenance, which is especially obvious in the dynamic agent. Dynamic proxies can process multiple methods at the same time through reflection, and if you use the decorator pattern, when there are more methods, the decorator class becomes complex.

Dynamic proxy is divided into jdk proxy and cglib proxy. The dynamic proxy of jdk is based on the interface implementation, and the proxied object must implement the interface, while cglib is based on the parent class implementation, which is more universal. Jdk and cglib are used to enhance the SInger class, respectively. The code is as follows:

Jdk mode:

Public class Singer_proxy {

Public static void main (String [] args) {

Final Singer singer = new Singer ()

Sing proxy = (Sing) Proxy.newProxyInstance (singer.getClass () .getClassLoader (), singer.getClass () .getInterfaces (), new InvocationHandler () {

@ Override

Public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {

System.out.println ("publicity.") ; / / the method can be extracted here to achieve isolation between businesses

Object invoke = method.invoke (singer, args)

System.out.println ("the end...") ; / / ditto

Return invoke

}

});

Proxy.song ()

}

}

Cglib mode:

Public class Singer_proxy {

Public static void main (String [] args) {

Final Singer singer = new Singer ()

Enhancer enhancer = new Enhancer ()

Enhancer.setSuperclass (Singer.class)

Enhancer.setCallback (new MethodInterceptor () {

@ Override

Public Object intercept (Object o, Method method, Object [] objects, MethodProxy methodProxy) throws Throwable {

System.out.println ("publicity.")

Object invoke = method.invoke (singer, objects)

System.out.println ("the end...")

Return invoke

}

});

Singer proxy = (Singer) enhancer.create ()

Proxy.sing ()

}

}

Spring's AOP (Aspect Oriented Programming) is aspect-oriented programming, and its underlying layer is implemented using dynamic proxies. Cglib is integrated inside Spring, which will determine whether to use jdk or cglib to implement object proxies according to whether the object implements the interface. Of course, it can also be explicitly set to always use cglib proxies.

AOP can isolate each part of the business logic, which greatly reduces the coupling between the various parts of the business logic, and improves the reusability of the program and the efficiency of development. AOP vividly embodies the idea of "high cohesion, low coupling" of java code.

The AOP of Spring encapsulates the dynamic proxy. Through the way of configuration, we can dynamically generate the proxy object during the run, intervene in the enhanced function when the method of the proxy object is executed, and call the method of the target object, so as to enhance the function. By configuring five "notification" types: "pre-notification", "post-notification", "surround notification", "exception-thrown notification" and "final notification" ("notification" is a term in aspect-oriented programming, when you intercept the method of the object to be enhanced, what to do is called "notification"), decide where to add the corresponding function, and actually surround the notification to achieve the function of all other notifications. The code is shown below, so most of the time we use surround notifications directly.

Public Object around (ProceedingJoinPoint pjp) throws Throwable {

Try {

System.out.println ("advance notice.")

Object [] args = pjp.getArgs ()

Object proceed = pjp.proceed (args)

System.out.println ("Post notice.")

Return proceed

} catch (Exception e) {

E.printStackTrace ()

System.out.println ("exception throw notification.")

} finally {

System.out.println ("final notice.")

}

Return null

}

The declarative transaction management of Spring, whose bottom layer is also realized through AOP, uses surround notification, so it is very convenient to do transaction management for all kinds of business. Because of the good decoupling of dynamic agents, this technology is actually used in many frameworks.

After reading the above, have you mastered how to enhance the functionality of a class in Java? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report