Design pattern series: Singleton pattern

Curly bracket MC 2021-10-14 06:43:52
design pattern series singleton pattern


original : Curly braces MC( WeChat official account :huakuohao-mc). Focus on JAVA Basic programming and big data , Focus on experience sharing and personal growth .

The singleton pattern, as the name suggests , Is to ensure that a class in the system has only one unique object instance . This demand is often encountered in the actual development process .

Singleton mode can be implemented in two ways , One is called Hungry Chinese style , One is called Slacker type .

Let's take a look first UML chart :


Hungry Chinese style

It's called a hungry man , Because this implementation is when the class is loaded Of The object is initialized at the time , And through JVM The class loading mechanism ensures that there is only one class instance in the system .

Let's first look at the complete code of hungry Han style

public class SingleObject {

    //create an object  of SingleObject
    private static SingleObject instance = new SingleObject();

    //make the constuctor private so that this class cannot be instantiated
    private SingleObject(){}

    public static SingleObject getInstance(){
        return instance;
    }

    public void showMessage(){
       System.out.println("I'm eager");
    }
}

The key code of hungry Chinese style is on the first line , adopt static The keyword is decorated instance The variable , This initializes when the class is loaded SingleObject.

Slacker type

The so-called lazy style is to create objects when needed , Lazy style is more complicated , Locking and double checking mechanism is needed to ensure that in multi-threaded environment , Only one instance is created . The complete code is as follows

public class LazySingleObject {

    private volatile static LazySingleObject instance = null;

    private LazySingleObject() {}

    public static LazySingleObject getInstance(){
        // First check
        if (instance == null){
            synchronized (LazySingleObject.class){
               // Second inspection
                if (instance == null){
                    instance = new LazySingleObject();
                }
            }
        }
        return instance;
    }
    
    public void showMessage(){
        System.out.println("I'm lazy");
    }
    
}

This uses the singleton pattern

SingleObject object = SingleObject.getInstance();
//show the message
object.showMessage();

summary

The singleton pattern is also one of the creation patterns , When implementing this pattern, the instance variable should be set to static , Second, constructors must become private , Prevent external references and create objects . It's easier to implement the hungry Han style , But initializing the instance object is time-consuming and resource consuming , It will waste time and resources when the system starts up ; Lazy, on the other hand, initializes when needed , It will not occupy system startup resources , But it's more difficult to implement , Especially in the case of multithreading , Unless there are special requirements , Otherwise, it is recommended to use hungry Han style .

Recommended reading

1. Java Concurrent programming things ( Ten )—— Final summary

2. Common network problem location tools that programmers should master

3. Awk Can you use this ancient magic weapon

4. Hand in hand to teach you to build a set of ELK Log search operation and maintenance platform

·END·
 


版权声明
本文为[Curly bracket MC]所创,转载请带上原文链接,感谢
https://javamana.com/2021/10/20211002145640763r.html

  1. Hadoop Foundation - 03 - hdfs (Hadoop Distributed File System) Basic Concepts
  2. Hadoop Foundation - 05 - hdfs Project (word Frequency Statistics)
  3. Hadoop Foundation - 06 - hdfs Data Read and write
  4. The "monthly test" report card of the new car built under the lack of core: Xiaopeng and Weilai took the lead in "breaking 10000", and the ideal plummeted by 25%
  5. Introduction to making arch linux software package
  6. Hard core observation 407 HTTPS everywhere browser extension is about to retire
  7. How to use busybox on Linux
  8. In 2021, the talent incentive plan of Linux foundation open source software School Park was officially launched
  9. It's not windows or Linux. Shrink is the "God operating system"
  10. Install anydesk on Ubuntu Linux
  11. 2021, can we recommend using Linux to play games?
  12. not exist:org.springframework.kafka.listener.AbstractMessageListenerContaingetContainerProperties()
  13. Are you sure HTTPS is asymmetric encryption for content encryption? See the answers and reasons
  14. MySQL online slow log query
  15. Java JDK server installation
  16. 手把手教你使用Java开发在线生成pdf文档
  17. Questions d'entrevue dans la base de données MySQL (dernière version 2021)
  18. Java零基础小白入门必做题汇总(建议收藏)第一篇
  19. Day15 Java Foundation
  20. Day16 Java Foundation
  21. Day17 Java Foundation
  22. Day18 Java Foundation
  23. Linux installe JDK 1.8 et configure les variables d'environnement
  24. Tutoriel d'utilisation Maven super détaillé
  25. Spring boot reads project parameter configuration
  26. Docker installing rocketmq
  27. Java Zero Basic small white Beginner must make a summary of issues (recommended Collection) Chapitre 1
  28. Manuel pour vous apprendre à utiliser le développement Java pour générer des documents PDF en ligne
  29. 40 + comment les femmes s'habillent - elles pour montrer leur jeunesse?Un manteau et une jupe vous donnent un look haut de gamme tout au long de l'automne et de l'hiver
  30. Tutoriel d'installation Ubuntu 16.04 / Hadoop 3.1.3Configuration autonome / pseudo - distribuée
  31. L'apprentissage le plus détaillé de springboot à l'échelle du réseau - day01
  32. L'apprentissage le plus détaillé de springboot sur le Web - day02
  33. L'apprentissage le plus détaillé de springboot sur le Web - day03
  34. L'apprentissage le plus détaillé de springboot sur le Web - day04
  35. Tutoriel d'utilisation Maven super détaillé
  36. L'apprentissage le plus détaillé de springboot sur le Web - day05
  37. L'apprentissage le plus détaillé de springboot sur le Web - day06
  38. L'apprentissage le plus détaillé de springboot sur le Web - day07
  39. Introduction to JavaScript - write a photo album for your girlfriend
  40. [Hadoop 3. X] HDFS storage type and storage strategy (V) overview
  41. L'apprentissage le plus détaillé de springboot sur le Web - day08
  42. Introduction à la page Web de rabbitmq (3)
  43. No Converter found for return value of type: class java.util.arraylist Error Problem
  44. (16) , spring cloud stream message driven
  45. Que faut - il apprendre de l'architecture des microservices Spring Cloud?
  46. Résolution: erreur: Java: distribution cible invalide: 11problème d'erreur
  47. Springboot démarre en une minute et sort de l'enfer de la configuration SSM!
  48. Maven - un outil de gestion essentiel pour les grands projets d'usine, de l'introduction à la maîtrise![️ Collection recommandée]
  49. ️ Push to interview in Large Factory ᥧ - - Spring Boot Automatic Assembly Principle
  50. [️ springboot Template Engine] - thymeleaf
  51. Springboot - MVC Automatic configuration Principle
  52. Mybatis reverse engineering and the use of new version mybatisplus 3.4 reverse engineering
  53. Base de données MySQL - transactions et index
  54. Sécurité du printemps - [authentification, autorisation, déconnexion et contrôle des droits]
  55. Moteur de base de données InnoDB diffère de myisam
  56. Swagger - [springboot Integrated Swagger, configure Swagger, configure scan Interface, configure API Group]
  57. Cadre de sécurité Shiro - [QUICKstart, login Block, User Authentication, request Authorization]
  58. [Introduction à Java] installation de l'environnement de développement - Introduction à Java et construction de l'environnement
  59. 【 linux】 notes d'utilisation tmux
  60. MySQL + mybatis paging query - database series learning notes