My views on Singleton mode and my views on Mode
The Singleton mode is the most common design mode. If you want to enter a large company, you must thoroughly master the singleton mode and summarize some common Singleton modes.
First of all, it is the most simple cool-man mode. The cool-man mode is the simplest Singleton mode.
/*** Invalid mode */public class SingleTon {private static final SingleTon instance = new SingleTon (); private SingleTon () {} public static SingleTon getInstance () {return instance ;}}
It is actually the lazy loading mode. The simplest lazy loading mode is as follows:
public class SingleTon {private static SingleTon instance = null ;private SingleTon(){}public static SingleTon getInstance() {if (instance == null) {instance = new SingleTon();}return instance;}}
However, the preceding lazy mode is thread insecure and can be locked.
public class SingleTon {private static SingleTon instance = null ;private SingleTon(){}public static synchronized SingleTon getInstace(){if (instances == null ) {return instances = new SingleTon();}return instances;}}
Or double lock mode
public class SingleTon {private static SingleTon instance = null ;private SingleTon(){}public static SingleTon getInstance(){if (instances == null) {synchronized (SingleTon.class) {instances = new SingleTon();}}return instances;}}
The Singleton mode can also be implemented using internal classes.
public class SingleTon { public static class SingleTonHolder{private static SingleTon instance = new SingleTon();}public SingleTon() {}public static SingleTon getInstance() {return SingleTonHolder.instance;}}
Let's see how Daniel Jon Skeet writes a singleton (c)
public sealed class Singleton{ Singleton() { } public static Singleton Instance { get { return Nested.instance; } } class Nested { // Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit static Nested() { } internal static readonly Singleton instance = new Singleton(); }}
Contact your huwei08@baidu.com if you have any questions
What is Singleton mode?
Hello, you can start with a question: how can I instantiate a class only once in java?
The answer is: Singleton mode.
The code is embodied in
Public class {
Private A () {}// set the constructor to private, and other classes cannot be called for instantiation.
Private static A instance = new A (); // the only instance with the static attribute added.
Public static A getInstance () {// the only entry for other classes to call A, which is also A static attribute. The call method is A. getInstance ()
Return instance;
}
}
Singleton Mode
Only new instances can be created.
Your getInstance method only returns the reference of the EagerSingleton object and does not use new. Of course it is a singleton.