In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to use the design pattern of Java". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to use the design pattern of Java.
Design patterns are a way to make your code easier to modify by dividing parts that remain the same and those that change frequently.
If nothing happens, everyone who works on a programming project may think the same way. Especially for industrial-level projects, where dozens or even hundreds of developers usually work; the collaborative process shows that there must be standards and rules to make the code more elegant and adapt to change. That's why we have object-oriented programming (OOP) and software framework tools. The design pattern is somewhat similar to OOP, but it evolves further by treating change as part of the natural development process. Basically, design patterns take advantage of some OOP ideas, such as abstractions and interfaces, but focus on the process of change.
When you start a development project, you often hear the term refactoring, which means changing the code to make it more elegant and reusable; that's where the design pattern shines. When you are dealing with existing code (whether built by others or by yourself in the past), understanding design patterns can help you look at things differently, and you will find problems and ways to improve the code.
There are many design patterns, of which singleton pattern, factory pattern and observer pattern are the most popular, and I will introduce them one by one in this article.
Singleton mode: avoid creating one object at a time
The singleton pattern singleton pattern is a very popular design pattern, and its implementation is relatively simple because you only need one class. However, many developers debate whether the advantages of singleton design pattern outweigh the disadvantages because it lacks obvious benefits and is easy to be abused. Few developers implement singletons directly; instead, programming frameworks such as Spring Framework and Google Guice have built-in singleton design patterns.
But understanding the singleton pattern is still of great use. The singleton pattern ensures that a class is created only once and provides a global access point to it.
Singleton mode: ensure that only one instance is created and avoid creating multiple instances in the same project.
The following figure shows a typical class object creation process. When the client requests to create an object, the constructor creates or instantiates an object and calls the method to return the class to the caller. But every time an object is requested, the constructor is called, a new object is created, and it returns a unique object. I guess the creators of object-oriented languages have a reason to create a new object every time, but proponents of the singleton process say it is redundant and a waste of resources.
Normal class instantiation
The following figure uses singleton mode to create objects. Here, the constructor is called only when the object calls the predesigned getInstance () method for the first time. This is usually done by checking that the value is null, and that the object is stored inside the singleton class as a private variable. The next time getInstance () is called, the class returns the object that was created for the first time. No new object is generated; it just returns the old one.
Singleton pattern instantiation
The following code shows the easiest way to create a singleton pattern:
Package org.opensource.demo.singleton; public class OpensourceSingleton {private static OpensourceSingleton uniqueInstance; private OpensourceSingleton () {} public static OpensourceSingleton getInstance () {if (uniqueInstance = = null) {uniqueInstance = new OpensourceSingleton ();} return uniqueInstance;}}
On the caller, this shows how to call the singleton class to get the object:
Opensource newObject = Opensource.getInstance ()
This code validates the idea of the singleton pattern:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
When getInstance () is called, it checks whether the object has been created by checking the null value.
If the value is null, it creates a new object and saves it to the private domain, returning the object to the caller. Otherwise, the previously created object is returned directly.
The main problem with singleton pattern implementation is that it ignores parallel processes. This problem arises when multiple processes use threads to access resources simultaneously. There is a corresponding solution for this situation, which is called a double-checked lock and is used for multithread safety, as follows:
Package org.opensource.demo.singleton; public class ImprovedOpensourceSingleton {private volatile static ImprovedOpensourceSingleton uniqueInstance; private ImprovedOpensourceSingleton () {} public static ImprovedOpensourceSingleton getInstance () {if (uniqueInstance = = null) {synchronized (ImprovedOpensourceSingleton.class) {if (uniqueInstance = = null) {uniqueInstance = new ImprovedOpensourceSingleton ();} return uniqueInstance;}}
Re-emphasize the previous point and make sure that your singleton pattern is implemented directly only if you think it is a safe option. The best way is to take advantage of singleton functionality by using a well-made programming framework.
Factory mode: delegate object creation to the factory class to hide the creation logic
The factory pattern factory pattern is another well-known design pattern, but with a little bit of complexity. There are many ways to implement the factory pattern, and the following code example is the simplest. To create an object, the factory pattern defines an interface that allows its subclasses to decide which class to instantiate.
Factory mode: delegate object creation to the factory class, so it hides the creation logic.
The following picture shows how the simplest factory pattern is implemented.
Factory pattern
Instead of calling object creation directly, the client requests the factory class to create an object of type x. Depending on its type, the factory pattern determines the objects to be created and returned.
In the following code example, OpensourceFactory is a factory class implementation that takes the type from the caller and determines which object to create and return based on that input value:
Package org.opensource.demo.factory; public class OpensourceFactory {public OpensourceJVMServers getServerByVendor ([String] [18] name) {if (name.equals ("Apache")) {return new Tomcat ();} else if (name.equals ("Eclipse")) {return new Jetty ();} else if (name.equals ("RedHat")) {return new WildFly () } else {return null;}
OpenSourceJVMServer is a 100% abstract class (that is, an interface class) that indicates what to implement, not how:
Package org.opensource.demo.factory; public interface OpensourceJVMServers {public void startServer (); public void stopServer (); public [String] [18] getName ();}
This is an implementation example of the OpensourceJVMServers class. When RedHat is passed to the factory class as a type, the WildFly server is created:
Package org.opensource.demo.factory; public class WildFly implements OpensourceJVMServers {public void startServer () {[System] [19] .out.println ("Starting WildFly Server...");} public void stopServer () {[System] [19] .out.println ("Shutting Down WildFly Server...");} public [String] [18] getName () {return "WildFly" Observer mode: subscribe to topics and get notifications of relevant updates
Finally, there is the observer mode observer pattern. Like the singleton pattern, few professional programmers directly implement the observer pattern. However, many message queuing and data service implementations borrow the concept of the Observer pattern. The observer pattern defines one-to-many dependencies between objects, and when the state of an object changes, all objects that depend on it are automatically notified and updated.
Observer mode: if there are updates, clients that subscribe to the topic / topic will be notified.
The easiest way to understand the Observer pattern is to imagine a mailing list from which you can subscribe to any topic, whether it's open source, technology, celebrity, cooking, or anything else you're interested in. Each topic maintainer has a list of its subscribers, which are equivalent to observers in observer mode. When a topic is updated, all its subscribers (observers) will be notified of the change. And subscribers can always unsubscribe to a topic.
As shown in the following figure, clients can subscribe to different topics and add observers to get notifications of the latest information. Because the observer is constantly listening to the topic, the observer notifies the client of any changes.
Observer pattern
Let's take a look at the code example of the observer pattern, starting with the topic / topic class:
Package org.opensource.demo.observer; public interface Topic {public void addObserver ([Observer] [22] observer); public void deleteObserver ([Observer] [22] observer); public void notifyObservers ();}
This code describes an interface to implement defined methods for different topics. Notice how an observer is added, removed, and notified.
This is an example of an implementation of a theme:
Package org.opensource.demo.observer; import java.util.List;import java.util.ArrayList; public class Conference implements Topic {private List listObservers; private int totalAttendees; private int totalSpeakers; private [String] [18] nameEvent; public Conference () {listObservers = new ArrayList ();} public void addObserver ([Observer] [22] observer) {listObservers.add (observer) } public void deleteObserver ([Observer] [22] observer) {int I = listObservers.indexOf (observer); if (I > = 0) {listObservers.remove (I);}} public void notifyObservers () {for (int item0, nObservers = listObservers.size (); I < nObservers; + + I) {[Observer] [22] observer = listObservers.get (I) Observer.update (totalAttendees,totalSpeakers,nameEvent);}} public void setConferenceDetails (int totalAttendees, int totalSpeakers, [String] [18] nameEvent) {this.totalAttendees = totalAttendees; this.totalSpeakers = totalSpeakers; this.nameEvent = nameEvent; notifyObservers ();}}
This code defines the implementation of a specific theme. When a change occurs, the implementation calls its own method. Note that this will get the number of observers, which is stored as a list, and can notify and maintain observers.
This is an observer class:
Package org.opensource.demo.observer; public interface [Observer] [22] {public void update (int totalAttendees, int totalSpeakers, [String] [18] nameEvent);}
This class defines an interface that different observers can implement to perform specific operations.
For example, an observer who implements this interface can print out the number of attendees and speakers at the meeting:
Package org.opensource.demo.observer; public class MonitorConferenceAttendees implements [Observer] [22] {private int totalAttendees; private int totalSpeakers; private [String] [18] nameEvent; private Topic topic; public MonitorConferenceAttendees (Topic topic) {this.topic = topic; topic.addObserver (this);} public void update (int totalAttendees, int totalSpeakers, [String] [18] nameEvent) {this.totalAttendees = totalAttendees; this.totalSpeakers = totalSpeakers This.nameEvent = nameEvent; printConferenceInfo ();} public void printConferenceInfo () {[System] [19] .out.println (this.nameEvent + "has" + totalSpeakers + "speakers and" + totalAttendees + "attendees");}} so far, I believe you have a deeper understanding of "how to use the Java design pattern", you might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.