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

What are the characteristics of reflection and factory design patterns

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces "what are the characteristics of reflection and factory design patterns". In daily operation, I believe that many people have doubts about the characteristics of reflection and factory design patterns. I have consulted all kinds of materials and sorted out simple and useful operation methods. I hope it will be helpful for you to answer the doubts about "what are the characteristics of reflection and factory design patterns?" Next, please follow the editor to study!

Reflection and Factory Design pattern

If you want to instantiate an object, you can use the reflection mechanism in addition to the keyword new, so you must think about the question: why provide an instantiation of reflection? So do you use the keyword new or reflection?

If you want to better understand such problems, the best solution is to solve them through the factory design pattern.

The biggest feature of the factory pattern: the client program class is not directly related to the instantiation management of the object, but only associated with the interface, through the factory class to obtain the instantiated object of the specified interface.

Example: traditional factory design pattern

Interface IMessage {public void send (); / / messaging} class NetMessage implements IMessage {public void send () {System.out.println ("[network messaging] www.mldn.cn");}} public class JavaAPIDemo {public static void main (String [] args) throws Exception {IMessage msg = new NetMessage (); / / if directly instantiated, there must be coupling problems}}

In actual development, the main role of the interface is to provide an operational standard for different layers. However, if a subclass is directly set as an interface instantiation operation at this time, there must be a coupling problem, so the factory design pattern is used to solve this problem.

Example: using factory design patterns to solve the problem

Public class JavaAPIDemo {public static void main (String [] args) throws Exception {IMessage msg = Factory.getInstance ("netmessage"); msg.send (); / [Network messaging] www.mldn.cn}} interface IMessage {void send (); / / messaging} class NetMessage implements IMessage {public void send () {System.out.println ("[Network messaging] www.mldn.cn") }} class Factory {private Factory () {} / / does not produce the meaning of instantiated objects, so the construction method privatizes public static IMessage getInstance (String className) {if ("netmessage" .equals IgnoreCase (className)) {return new NetMessage ();} return null;}}

Static factory design pattern

This factory design pattern belongs to the static factory design pattern, that is, if a subclass is to be appended now, it means that the factory class must make changes, because the specified interface object cannot be obtained without additional judgment.

Example: append a subclass to IMessage

Public class JavaAPIDemo {public static void main (String [] args) throws Exception {/ / IMessage msg = Factory.getInstance ("netmessage"); / / msg.send (); / / [Network messaging] www.mldn.cnIMessage msg = Factory.getInstance ("cloudmessage"); msg.send (); / / [Cloud messaging] www.mldnjava.cn}} interface IMessage {void send () / / messaging} class NetMessage implements IMessage {@ Overridepublic void send () {System.out.println ("[network messaging] www.mldn.cn");}} class CloudMessage implements IMessage {@ Overridepublic void send () {System.out.println ("[cloud messaging] www.mldnjava.cn");}} class Factory {private Factory () {} public static IMessage getInstance (String className) {if ("netmessage" .equalsIgnoreCase (className)) {return new NetMessage () } else if ("cloudmessage" .equals IgnoreCase (className)) {return new CloudMessage ();} return null;}}

The factory design pattern is the most effective solution to the coupling problem between the subclass and the client, but the core idea of the solution is to provide a factory class as a transition, but with the progress of the project, the IMessage interface may have more and more subclasses, and with the passage of time, more and more subclasses may be generated, so this means that the factory class will always be modified and will never stop.

Then the best solution at this point is not to use the keyword new, because the keyword requires a clear class to exist when new is used. The newInstance () method only needs a string that explicitly represents the class name.

Public class JavaAPIDemo {public static void main (String [] args) throws Exception {IMessage msg = Factory.getInstance ("cn.mldn.demo.NetMessage"); msg.send (); / [Network messaging] www.mldn.cn}} interface IMessage {void send (); / / messaging} class NetMessage implements IMessage {public void send () {System.out.println ("[Network messaging] www.mldn.cn") }} class CloudMessage implements IMessage {@ Overridepublic void send () {System.out.println ("[cloud messaging] www.mldnjava.cn");}} class Factory {private Factory () {} public static IMessage getInstance (String className) {IMessage instance = null;try {instance = (IMessage) Class.forName (className). GetDeclaredConstructor (). NewInstance ();} catch (Exception e) {e.printStackTrace () } return instance;}}

At this time, it can be found that the biggest advantage of the factory design pattern implemented by the reflection mechanism is that the expansion of the interface subclass will no longer affect the definition of the factory class.

However, further consideration is still needed, because in the actual project development process, there may be a large number of interfaces, and these interfaces may need to be instantiated by the factory class, so the factory design pattern at this time should not only serve the IMessage interface, but should serve all interfaces.

Public class JavaAPIDemo {public static void main (String [] args) throws Exception {IMessage msg = Factory.getInstance ("cn.mldn.demo.NetMessage", IMessage.class); msg.send (); / [Network messaging] www.mldn.cnIService service=Factory.getInstance ("cn.mldn.demo.HouseService", IService.class); service.service (); / / [Service] to provide services for your accommodation. }} class Factory {private Factory () {} / * get the interface instantiation object * @ param className interface subclass * @ param clazz describes the type of an interface * @ return if the subclass exists, return the instantiated object of the specified interface * / @ SuppressWarnings ("unchecked") public static T getInstance (String className,Class clazz) {T instance=null Try {instance= (T) Class.forName (className). GetDeclaredConstructor (). NewInstance ();} catch (Exception e) {e.printStackTrace ();} return instance;}} interface IService {void service ();} class HouseService implements IService {@ Overridepublic void service () {System.out.println ("[Service] provides services for your accommodation.") ;} interface IMessage {void send (); / / messaging} class NetMessage implements IMessage {public void send () {System.out.println ("[network messaging] www.mldn.cn");}} class CloudMessage implements IMessage {@ Overridepublic void send () {System.out.println ("[cloud messaging] www.mldnjava.cn");}}

At this point, the factory mode will no longer be limited to the specified interfaces, but can provide instantiated services for all interfaces to achieve reusability.

At this point, the study of "what are the characteristics of reflection and factory design patterns" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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

Development

Wechat

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

12
Report