In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
Most people do not understand the knowledge points of this article "how to master the singleton mode of Java", so the editor summarizes the following, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to master the singleton mode of Java" article.
Singleton pattern: first of all, there are 23 design patterns in Java:
Creative pattern: factory method pattern, abstract factory pattern, singleton pattern, builder pattern, prototype pattern
Structural patterns: adapter pattern, decorator pattern, proxy pattern, appearance pattern, bridging pattern, combination pattern, sharing meta-pattern
Behavioral model: policy model, template method model, observer model, iterative sub-model, chain of responsibility model, command mode, memo mode, state mode, visitor mode, intermediary mode, interpreter mode.
1. What is the singleton mode:
Definition:
A pattern in which a class has only one instance and the class can create the instance on its own. It can avoid the waste of memory resources caused by opening multiple task manager windows, or errors such as inconsistent display content of each window. For example, can our computer only open one task manager? Right? this is to prevent waste of resources and other mistakes.
In a project, you can usually get the same object through the singleton pattern to call the tool method, which has the advantage of saving memory resources. I don't need to create multiple different objects because it consumes memory resources.
In short: the singleton is that the program has only one instance, and this class is responsible for creating its own object, while making sure that only one object is created.
Characteristics of the singleton model:
Constructor private
Hold attributes of your own type
Provide a static method to obtain an instance
The structure diagram of the singleton pattern:
2. Advantages and disadvantages of singleton model:
Advantages:
Reduced memory overhead
Avoid multiple occupations of resources
Set global access points to optimize and share access to resources
Disadvantages (refer to the Internet):
Generally, there is no interface, so it is difficult to expand. If you want to expand, there is no second way to violate the principle of opening and closing except to modify the original code.
In concurrent testing, singleton mode is not conducive to code debugging. During debugging, if the code in the singleton is not finished, a new object cannot be generated by simulation.
The functional code of the singleton pattern is usually written in a class, and if the functional design is unreasonable, it is easy to violate the principle of single responsibility.
Look at a mind map of singleton mode:
3. Lazy mode (more commonly used)
Lazy mode is characterized by delayed initialization, and the object is instantiated only when the method is called to get the instance.
Thread is not safe, strictly speaking, it is not a singleton mode. The advantage is that objects will be created only when the instance is obtained, thus saving memory overhead.
Demo:
Public class SingLeton {/ / 1, has its own type of attribute private static SingLeton instance; / / 2, Constructor privatization private SingLeton () {} / / 3, static method public static SingLeton getInstance () {if (instance = = null) {instance = new SingLeton ();} return instance;}}
Test class:
Public class Test {public static void main (String [] args) {/ / determine whether the same object SingLeton S1 = SingLeton.getInstance (); SingLeton S2 = SingLeton.getInstance (); System.out.println (S1 = = S2);}}
Output:
True Note:
About lazy mode thread unsafe
Now that you know that lazy mode threads are unsafe, you need to use synchronized to synchronize:
/ * make sure that instance synchronizes in all threads * / public class SingLeton2 {/ / 1, with its own type of attribute private static volatile SingLeton2 instance / / 2. The constructor privatizes private SingLeton2 () {} public static synchronized SingLeton2 getInstance () {/ / getInstance method preceded by synchronous if (instance = = null) {instance = new SingLeton2 ();} return instance;}}
If you are writing multithreading, do not delete the keywords volatile and synchronized in the above example code, otherwise there will be thread unsafe issues. Thread safety can be ensured without deleting these two keywords, but synchronizing each access will affect performance and consume more resources, which is the disadvantage of lazy singletons.
4. Hungry man mode [recommended]
The hungry mode is thread-safe and commonly used, but it is easy to generate junk objects, because the hungry mode is initialized as soon as the class is loaded.
Give an example
Demo:
/ * * hungry mode * / public class SingLeton {/ / holds its own type of properties (like slackers) / / due to static modification, it is executed only once when the class is loaded, and the object private static SingLeton instance = new SingLeton () is instantiated when the class is loaded; / / the constructor is privatized and cannot be used to create an object private SingLeton () {} / / provide the static method public static SingLeton getInstance () {return instance;}} to obtain the instance
Test class:
Public class Test {public static void main (String [] args) {/ / determine whether the same object SingLeton S1 = SingLeton.getInstance (); SingLeton S2 = SingLeton.getInstance (); System.out.println (S1 = = S2);}}
Output:
True
Comparison between the lazy model and the hungry model:
Lazy mode delayed loading, non-thread safe, hungry mode thread safe
Lazy mode has just run uninstantiated objects, and instantiated objects only when needed, which is equivalent to saving memory overhead.
The hungry mode will initialize it for you as long as it runs and loads the class, so you need to use more memory.
Illustration:
5. Application scenarios of singleton mode:
Some classes that need to be created frequently can reduce the memory pressure of the system by using singletons.
This class requires only one object to be generated, such as everyone's name.
Class takes a lot of resources to create an instance, or instantiation takes a long time, and is often used
Objects that frequently access a database or file
Classes need to be instantiated frequently, and objects created are frequently destroyed, such as multithreaded thread pools
6. An application example of singleton model.
Here, the lazy singleton model is used to simulate the monitor of the class.
Analysis: in each semester, there is only one monitor of the class, so it is suitable to be realized by singleton mode.
Person class:
/ * use lazy mode * / public class Person {/ / make sure that instance synchronizes private static volatile Person instance; private Person () {System.out.println ("generate a monitor") in all threads;} / / add synchronized lock public static synchronized Person getInstance () {if (instance = = null) {instance = new Person () } else {System.out.println ("error message: there is already a monitor and can no longer be generated");} return instance;} public void getName () {System.out.println ("I am the monitor: Xiaoqiang");}}
Test class:
Public class Test {public static void main (String [] args) {Person p1 = Person.getInstance (); p1.getName (); / / output monitor name Person p2 = Person.getInstance (); p2.getName (); if (p1 = = p2) {System.out.println ("two squad leaders are the same person") } else {System.out.println ("two monitor is the same person");}
Running result:
Produce a monitor I am the monitor: Xiaoqiang error message: there is already a monitor, can no longer produce I am the monitor: Xiaoqiang two monitor is more than the same person is about "how to master the singleton mode of Java" this article content, I believe we all have a certain understanding, I hope the content shared by the editor will be helpful to you, if you want to know more about the relevant knowledge, please pay attention to the industry information channel.
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.