A single-instance pattern of Java design patterns
Recently because want to understand the bottom of the source code, so looked at some design patterns, follow-up to read several kinds of writing
Single-Case Pattern English Original:
- Ensure a class have only one instance,and provide a global point of access to it
- That is: Throughout the application, make sure that there is only one instance of a class and provide this instance to the entire system
There are typically two representations in Java
- A hungry man type Singleton: class is instantiated at load time
- Lazy Singleton: Loading is only instantiated the first time
1. A hungry man type single case
Singleton
static Singleton m_instance = new Singleton () |
|
Static getinstance (): Singleton |
|
Source:
publicclass Singleton{ privateSingleton() {} privatestaticfinalnewSingleton(); //静态工厂方法 publicstaticgetInstance() { return single; } }//成员变量是私有的,而且不能被外部访问
2, lazy-type single case
Singleton
static Singleton m_instance = null |
|
syncchronized static getinstance (): Singleton |
|
Source:
java public class Singleton { private Singleton() {} private static Singleton single=null; public static Singleton getInstance() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } } //双重校验锁
- The first one is more resource-intensive, but the speed of reflection is relatively good.
- The second is cool, but it consumes the performance of the runtime, but the impact is minimal.
- In the end, the first is more suitable for user resource configuration, the second is more suitable for the business logic of the singleton mode
With the help of: Electronic industry Press "design principles" Thanks!
A single-instance pattern of Java design patterns