Definition: Ensure that a class has only one instance, and instantiates it itself and provides this instance to the entire system.
Type: Create class pattern class diagram:
Class diagram knowledge points:
1. Class diagrams are divided into three parts, name, attributes, and methods.
2. Comment information starting with << and ending with >>
3. Modifier + represents public, - represents private, # represents protected, nothing represents the package visible.
4. Underlined attributes or methods represent static.
5. Friends who are not familiar with the relationship between objects in the class diagram can refer to the article: The relationship between classes in the design pattern.
The singleton mode should be the simplest mode among the 23 design modes. It has the following elements:
Let’s take a look at a simple example:
package com.wolf.action;import java.util.HashMap;import java.util.Map;public class demo { public static void main(String args[]) throws InstantiationException, IllegalAccessException, ClassNotFoundException { System.out.println(Son.getInstance().getName()); System.out.println("Who am I"); }}class Son extends Father { private String name = "Son"; final String CLASS = "demo"; protected String getName() { return this.query("aaa"); } public static Son getInstance() throws InstantiationException, IllegalAccessException, ClassNotFoundException { // This must be a global path, otherwise return (Son) instance("com.wolf.action.Son"); }}class Father { private static Map<String, Object> instance = new HashMap<String, Object>(); private String name = "Premium class"; protected void Fatcher() { System.out.println("I am the parent class"); } protected String query(String sql) { return sql + "has been done"; } public static Object instance(String objname) throws InstantiationException, IllegalAccessException, ClassNotFoundException { if (instance.get(objname) == null || !(instance.get(objname) instanceof Father)) { instance.put(objname, Class.forName(objname).newInstance()); } return instance.get(objname); }} The singleton pattern is divided into two types according to the timing of instantiating the object: one is the hungry singleton and the other is the lazy singleton. When the singleton class is loaded, the singleton instantiates an object to its own reference; the lazy style will instantiate the object only when the instance method is called. The code is as follows:
Hungry Man-style single case
public class Singleton { private static Singleton singleton = new Singleton(); private Singleton(){} public static Singleton getInstance(){ return singleton; } }Lazy single case
public class Singleton { private static Singleton singleton; private Singleton(){} public static synchronized Singleton getInstance(){ if(singleton==null){ singleton = new Singleton(); } return singleton; } }Advantages of singleton mode:
Applicable scenarios: Due to the above advantages of singleton mode, it is a design mode that is more commonly used in programming. I summarized what I know of suitable scenarios for using singleton mode:
Notes on singleton mode:
Some controversy about singleton pattern in java:
If an object in singleton mode is not used for a long time, will it be collected by the jvm garbage collector? I saw a lot of information saying: If a singleton object is not used in memory for a long time, it will be considered a garbage by jvm and will be cleaned up when performing garbage collection. I am skeptical about this statement. My own view is: In the hotspot virtual machine version 1.6, the jvm garbage collector will not recycle singleton objects unless the connection statically referenced to singleton objects in the singleton is artificially disconnected.
Regarding this controversy, the author wrote a separate article to discuss it. If you have different opinions or have experienced this, please enter the article singleton model discussion: singleton model and garbage collection participate in the discussion.
Will multiple singletons appear in a jvm
In the case of distributed systems, multiple class loaders, and serialized, multiple singletons will be generated, which is undoubtedly true. So will a singleton be generated in the same jvm? Only the same singleton can be obtained using the getInstance() method provided by the singleton, unless the reflection method is used, a new singleton will be obtained. The code is as follows
Class c = Class.forName(Singleton.class.getName()); Constructor ct = c.getDeclaredConstructor(); ct.setAccessible(true); Singleton singleton = (Singleton)ct.newInstance();
This way, each run will produce a new singleton object. Therefore, when using singleton mode, be careful not to use reflection to generate new singleton objects.
Is lazy singleton thread safe?
It is mainly some online statements that the lazy singleton pattern is thread-insecure. Even adding the synchronized keyword to the instantiation method is still dangerous. However, after encoding tests, I found that after adding the synchronized keyword to modify it, although it has a partial impact on performance, it is thread-safe and does not instantiate multiple objects.
Are there only two types of singleton modes: hungry and lazy styles?
Hungry singleton and lazy singleton are just two relatively mainstream and commonly used singleton pattern methods. Theoretically, any design pattern that can implement only one instance of a class can be called a singleton pattern.
Can singleton classes be inherited?
Since the construction method is private, they are not inheritable, but many other singleton patterns can be inherited, such as registered singletons.
Is it better to be a hungry singleton or a lazy singleton
In Java, the hungry singleton is better than the lazy singleton. In C++, lazy singletons are generally used.
The singleton pattern is relatively simple, so I won’t give an example code demonstration here.