Design patterns as a development (interview) knowledge, we still need to master. Don’t master well, that’s because you haven’t prepared a cheat sheet ~
What is a cheat sheet, is referring to other people’s answers, plus their own handwriting.
Cheat sheet Resources:
JAVA and Patterns singleton schema
Design pattern (2) seven writing methods of singleton pattern
The singleton pattern
Let’s copy a UML diagram
The data structure of the singleton pattern is simple, a single example object
Characteristics of the singleton pattern
- A single instance
- Created internally by itself
- Provides unique access instances for all objects
1. Hangry singleton
Very strange naming way, I do not know why so called, I dare not ask, first copy ~
public class SimpleSingleton {
// Static objects are created when the object is initialized
private static SimpleSingleton instance = new SimpleSingleton();
private SimpleSingleton(a) {}// Returns the created instance object
public static SimpleSingleton getInstance(a) {
returninstance; }}Copy the code
Hungry han type is actually a kind of image of the appellation. If you are hungry, you are in a hurry to create an object instance. If you are hungry, you create an object instance when you load the class. (copy)
In the process of class loading, when we initialize the object, the static attributes in the object will be initialized, so here we mainly use the related characteristics of class loading, so as to achieve the effect of singleton.
The characteristics of
- Space for time – programs that exist as soon as they start (tend to waste memory) and save creation time when you use them (feel like you don’t save much)- has major drawbacks
- Thread-safe — Initialization using class loading (static objects are initialized only once), thread-safe
Lazy singleton
We also do not know how to ridicule this name, first copy is right ~
public class LazySingleton {
// Don't initialize it to save space
private static LazySingleton instance;
private LazySingleton(a) {}// add a lock
public static synchronized LazySingleton getInstance(a) {
if (instance == null) {
instance = new LazySingleton();
}
returninstance; }}Copy the code
There is a non-thread-safe slacker pattern in the resources (answer), that is a brother, send propositions, do not copy
Slacker style is actually a more graphic title. Since you are lazy, there is no rush to create object instances. Object instances are not created until they are ready to be used. Lazy people don’t actually do their work until they can’t get away from it, so they don’t create object instances when they load objects. (Also copied)
The characteristics of
- Time for Space – this is initialized only when in use. Avoid wasting space resources
- Low concurrency –
synchronized
The crazy requests of the brother one by one at the door, slow response
3, DoubleCheckLock singleton (DoubleCheckLock)
Also do not know this English has spelled wrong, did not have to copy can only mask once, million a pair of ~
public class DCLSingleton {
// Volatile memory is visible, meaning updates can be seen in real time
private volatile static DCLSingleton instance = new DCLSingleton();
private DCLSingleton(a) {}public static DCLSingleton getInstance(a) {
if (instance == null) {
// Sister came in, arranged, just that one chance to cherish
synchronized (DCLSingleton.class) {
// If a brother comes in, throw him out
if (instance == null) {
// Initialize well
instance = newDCLSingleton(); }}}returninstance; }}Copy the code
Double-checked locking refers to: Not every enters the getInstance method need to be synchronized, but out of sync, first enter the method, first check the instance exists, if there is no to the synchronized block below, this is the first heavy inspection, after enters the synchronized block, check whether the instance again, if not, just in case of synchronous create an instance, this is the second check. In this way, you only need to synchronize once, reducing the time wasted in making multiple synchronized judgments. (Copy again)
This pattern relies heavily on the volatile keyword.
The purpose of the volatile keyword is that the variable that it modiates is written directly to memory to be shared with other threads, ensuring that the value of the variable is correctly fetched across multiple threads
The characteristics of
High resource utilization
– to solve theLazy mode
An awkward situation in which methods are lockeddefective
– High concurrency also has some drawbacks, although they are very rare
4, Static inner class singleton (Lazy Initialization holder class)
This time the name of the English copy ~ force grid up ~
public class LIHCSingleton {
private LIHCSingleton(a) {}// The inner class is not initialized during class loading
private static class SingletonHolder {
private static LIHCSingleton instance = new LIHCSingleton();
}
public LIHCSingleton getInstance(a) {
// The inner class is initialized when called
returnSingletonHolder.instance; }}Copy the code
Static inner class singleton – Similar to hungry, thread-safe singleton is implemented by JVM class loading mechanism, and the disadvantages of hungry are solved by static inner class lazy loading mechanism.
The characteristics of
The hungry mode
Have both advantages and disadvantages- Thread safety
- High resource utilization
- It is great ~
The relevant knowledge
What are class-level inner classes?
-
To put it simply, a class-level inner class is a member inner class that has a static modifier. Member inner classes that are not static are called object-level inner classes.
-
A class-level inner class is the static component of its outer class. Its objects have no dependencies on the outer class objects and can therefore be created directly. An instance of an object-level inner class is bound to an external object instance.
-
In a class-level inner class, static methods can be defined. A static method can only refer to a static member method or a member variable in an external class.
-
Class-level inner classes are members of their outer classes and are loaded only when they are first used.
5. Enumerate singletons
Finally, I’m almost done, Su Fu
public enum EnumSingleton {
singleton;
public void excute(a){
// Todo can do anything, you decide}}Copy the code
The default enumerated instances are created thread-safe and singleton in any case.
In Effective Java, enumerated types of single elements have become the best way to implement Singleton.
Using enumerations to implement singleton control is much cleaner and provides a serialization mechanism for free, which is fundamentally guaranteed by the JVM and absolutely prevents multiple instantiations. It is a cleaner, more efficient, and safer way to implement singleton control.
conclusion
Three points by struggle, seven points day doomed, the remaining 90 points, you come on oh ~ SAO years