当前位置:网站首页>Singleton mode
Singleton mode
2022-07-26 16:32:00 【Old [email protected]】
Classification of design patterns
Create pattern
The singleton pattern 、 Abstract factory pattern 、 Archetypal model 、 Builder pattern 、 Factory mode
Structural mode
Adapter pattern 、 Bridging mode 、 Decoration mode 、 Portfolio model 、 Appearance mode 、 The flyweight pattern 、 The proxy pattern
Behavioral patterns
Template method pattern 、 Command mode 、 Visitor mode 、 Iterator pattern 、 Observer mode 、 Intermediary model 、 Memo mode 、 Interpreter mode 、 The state pattern 、 The strategy pattern 、 Responsibility chain pattern
The singleton pattern
Introduction to single mode
The so-called singleton pattern , Is to take certain methods to ensure that in the whole software system , There can only be one object instance for a class , And this class only provides a method to get its object instance ; for example Hibernate Of SessionFactory, It acts as a proxy for the data source , And responsible for creating Session object ,SessionFactory It's not lightweight , In general , A project usually only needs one SessionFactory object
Hungry Chinese style ( static const )
/*** * @author shaofan * @Description A single case of hungry Han style , Static variables */
public class Hungry1 {
/** * Privatized constructor , Way to create objects outside */
private Hungry1(){
}
/** * Use static constants to create objects , Rely on class loading mechanism , Static variables are loaded only once during class initialization , So the created object is singleton */
private final static Hungry1 INSTANCE = new Hungry1();
/** * Get instance * @return */
public Hungry1 getInstance(){
return INSTANCE;
}
}
Advantages and disadvantages
- advantage : Written in simple , It is to complete instantiation during class loading through class loading mechanism , Avoid thread synchronization problems
- shortcoming : Instantiate when the class is installed , No lazy loading effect , If you have never used this instance from the beginning to the end , Memory is wasted
- This way is based on classloader The mechanism avoids the synchronization problem of multithreading , however ,instance When the class is loaded, it is pear blossom , In singleton mode, most of them call getInstance Method , But there are many reasons for class loading , So it's not certain there are other ways ( Or other static methods ) Causes the class to load , There is no need to use instance But initialize instance It does not achieve the effect of lazy loading
- This singleton mode is available , May cause memory waste ( You can use it if you promise to use it )
Hungry Chinese style ( Static code block )
/*** * @author shaofan * @Description Hungry Chinese style , Static code block */
public class Hungry2 {
private static Hungry2 instance;
/** * Privatized constructor , Prevent external new object */
private Hungry2(){
}
// Initialize the instance in a static code block
static {
instance =new Hungry2();
}
/** * Get instance * @return */
public static Hungry2 getINSTANCE() {
return instance;
}
}
Advantages and disadvantages
This method is the same as that of static variables , All use the class loading mechanism to complete the initialization of instances
Slacker type ( Thread unsafe )
/*** * @author shaofan * @Description Slacker type , Thread unsafe */
public class Lazy1 {
private static Lazy1 instance;
private Lazy1(){
}
/** * obtain instance First judge whether it is empty , If it is empty, create , If it is not empty, return ; But in a multithreaded environment , Multiple threads may be detected as null at the same time , Causes duplicate creation of * @return */
public static Lazy1 getInstance(){
if(instance==null){
instance = new Lazy1();
}
return instance;
}
}
Advantages and disadvantages
- It has the effect of lazy loading , But it can only be used in single thread
- If it's multithreaded , A thread has entered if Judgment block , There is no time to carry it out , Another thread also passed this judgment statement , This is the time to generate multiple instances
- In development , This method is not recommended
Slacker type ( Synchronization method )
/*** * @author shaofan * @Description Slacker type , Synchronization method */
public class Lazy2 {
private static Lazy2 instance;
private Lazy2(){
}
/** * Use synchronized Keyword synchronization getInstance Method , Ensure that only one thread enters this method at the same time , You won't create multiple instances * @return */
public static synchronized Lazy2 getInstance() {
if(instance==null){
instance = new Lazy2();
}
return instance;
}
}
Advantages and disadvantages
- advantage : Solved the thread unsafe problem
- shortcoming : Too inefficient , When each thread wants to get an instance of a class , perform getInstance() Methods should be synchronized . In fact, only one instantiation of this method is enough , Later, if you want to get an example directly return that will do ; Directly add synchronized Keyword will cause every call to be locked , Low efficiency
- In actual development , It is not recommended to use
Double check
/*** * @author shaofan * @Description Slacker type , Double check */
public class Lazy3 {
private static Lazy3 instance;
private Lazy3(){
}
/** * Synchronize code blocks through class locks , Multiple threads are aligned first instance Make null value judgment , Conduct the first round of inspection , A small number of threads will enter during the first creation , Only lock the thread when it is first created , Carry out the second level inspection * @return */
public Lazy3 getInstance(){
if(instance==null){
synchronized (Lazy3.class){
if(instance==null){
instance = new Lazy3();
}
}
}
return instance;
}
}
Advantages and disadvantages
- Double-Check The concept is often used in multithreaded development , As shown in the code , Two null value checks were performed , It will be locked the second time , This improves performance while ensuring thread safety
- Thread safety 、 Delay loading 、 More efficient
- In actual development , Recommended
Static inner class
/*** * @author shaofan * @Description Static inner class mode */
public class StaticInner {
private StaticInner(){
}
/*** * Static inner classes are not loaded when outer classes are loaded , Instead, it has its own startup and loading mechanism , Load when calling this class for the first time , It will also have the effect of lazy loading , At the same time, due to the single load characteristics of the class , * The examples are also single */
private static class Instance{
private static final StaticInner INSTANCE = new StaticInner();
}
public StaticInner getInstance(){
return Instance.INSTANCE;
}
}
Advantages and disadvantages
- This method uses the class loading mechanism to ensure that the initialization instance has only one thread
- The static internal class method will not be instantiated immediately when the external class is loaded , But when you need to instantiate , call getInstance Method , To load the inner class , To complete the instantiation
- The static properties of a class are initialized only when the class is first loaded , So here ,JVM Help us ensure thread safety , There will be no multiple threads initializing the class multiple times
- advantage : Thread safety , Using static inner classes to achieve delayed loading , Efficient
- Recommended
enumeration
/*** * @author shaofan * @Description Enumeration method */
public enum Singleton {
INSTANCE;
}
Advantages and disadvantages
- With the help of jdk1.5 Add enumeration to implement singleton mode , It can not only avoid threading problems , It also prevents deserialization from recreating new objects
- This way is still Effective Java The way the author advocates
- Recommended
Singleton pattern source code analysis
stay JDK in ,java.lang.Runtime The singleton mode is used 
Here we use the starving Han style singleton mode
summary
- Singleton mode ensures that there is only one object in the system memory , Save system resources , For some objects that need to be destroyed by frequently disassembling function keys , Using singleton mode can improve system performance
- When you need to instantiate a singleton class , You must use the corresponding method of obtaining instances , instead of new
- Scenario used in singleton mode : Objects that need to be created and destroyed frequently 、 Creating objects takes too much time or resources ( Heavyweight objects ), But also commonly used objects 、 Utility class object 、 Objects that frequently access databases or files ( For example, data source 、session The factory etc. )
版权声明
本文为[Old [email protected]]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/207/202207261514178887.html
边栏推荐
猜你喜欢

Finally, someone explained the red blue confrontation clearly

2022 latest Tibet Construction scaffolder (construction special operation) simulation exam questions and answers

PAT甲级 1049 Counting Ones

PAT甲级 1050 String Subtraction

技术风向标 | 云原生技术架构成熟度模型解读

Technology vane | interpretation of cloud native technology architecture maturity model

可信隐私计算框架“隐语”开源专家观点集锦

博途PLC顺序开关机功能块(SCL)
![[fluent -- advanced] packaging](/img/aa/bd6ecad52cbe4a34db75f067aa4dfe.png)
[fluent -- advanced] packaging

Pat grade a 1046 shortest distance
随机推荐
Bugku login1
Test cases should never be used casually, recording the thinking caused by the exception of a test case
Tdengine landed in GCL energy technology, with tens of billions of data compressed to 600gb
Comprehensively design an oppe homepage -- layout and initialization
2022 test questions and answers for the latest national fire facility operator (senior fire facility operator)
Advanced CAD exercises (I)
C#事件和委托的区别
广州市安委办发布高温天气安全防范警示提醒
综合设计一个OPPE主页--明星机型的设计
Internet Protocol
kubernetes之ReplicationController与ReplicaSet
Configmap of kubernetes
2022牛客暑期多校训练营1(ACDGIJ)
Modify the password of the root user of MySQL database
匿名方法和lambda表达式使用的区别
Comprehensively design an oppe homepage -- Design of star models
[RCTF2015]EasySQL
Alibaba cloud DMS MySQL cloud database report error, solve!!
终于有人把红蓝对抗讲明白了
Collection of open source expert opinions on trusted privacy computing framework "argot"