Home Java Javagetting Started Detailed introduction to singleton pattern

Detailed introduction to singleton pattern

Aug 10, 2020 pm 04:29 PM
Singleton pattern

Detailed introduction to singleton pattern

First of all, let’s take a look at the definition of the singleton pattern:

The singleton pattern is one of the simplest design patterns in Java and is a creational pattern. It provides A best way to create objects. The singleton pattern involves a single class that is responsible for creating its own objects while ensuring that only a single object is created.

(Recommended tutorial: java introductory tutorial)

In order to ensure that there is only one object in the memory, avoid frequent creation of objects that cause memory consumption, so that all This singleton object is used wherever this object needs to be called.

Next let’s look at the types of singleton patterns:

1. Lazy style

Lazy style means that the singleton will only be created when it is needed. object.

Lazy-style singleton pattern implementation:

public class Singleton {
	private static Singleton singleton;
	private Singleton(){
	
	}
	public static Singleton getInstance(){
		if (singleton == null) {
			singleton = new Singleton();
	    }
	    return singleton;
}
Copy after login

There is a problem with lazy-style singleton implementation, that is, how to ensure that only one object is created? If two or more threads determine that singleton is empty at the same time, multiple objects will be created. Therefore we need to solve the thread safety problem.

When it comes to thread safety, what comes to mind is locking. Locking is nothing more than locking on methods or class objects.

//在方法上加锁
public class Singleton {
	private static Singleton singleton;
	private Singleton(){}
	public static synchronized Singleton getInstance() {
    	if (singleton == null) {
        	singleton = new Singleton();
    	}
    return singleton;
	}
}

//在类对象上加锁
public class Singleton {
	private static Singleton singleton;
	private Singleton(){}
	public static Singleton getInstance() {
    synchronized(Singleton.class) {   
        if (singleton == null) {
            singleton = new Singleton();
        }
    }
    return singleton;
	}	
}
Copy after login

These two methods can solve the problem of multi-threads creating singleton objects at the same time, but each time you obtain the object, you need to acquire the lock first, and the concurrency performance is poor. Therefore, optimization is still needed. The optimization goal is: if there is no instantiated object, lock and create it. If there is an instantiated object, return directly.

(Learning video recommendation: java course)

For locking on a method, locking is required regardless of whether there is an instantiated object. Therefore, what we need to optimize is to lock the class object.

//DCL单例模式(Double Check + Lock)
public class Singleton {
	//volatite关键词防止指令重排序,下文介绍
	private static volatile Singleton singleton;
	private Singleton(){}
	public static Singleton getInstance() {
	//如果singleton不为空,则直接返回对象,若多个线程发现singleton为空,则进入分支
		if (singleton == null) {
		//多个线程同时争抢一个锁,只有一个线程能成功,其他线程需等待
			synchronized(Singleton.class) {
			//争抢到锁的线程需再次判断singleton是否为空,因为有可能被上个线程实例化了
			//若不为空则实例化,后续线程再进入的时候则直接返回该对象
			//对于之后所有进入该方法的线程则无需获取锁,直接返回对象   
        	if (singleton == null) {
           		singleton = new Singleton();
        	}
    		}
		}
    	return singleton;
	}	
}
Copy after login

The volatile keyword is added to the above code to prevent instruction reordering.

2. Hungry Chinese style

Hungry Chinese style means that the singleton object is created when the class is loaded.

Hungry Chinese style singleton pattern implementation:

public class Singleton {
	private static final Singleton singleton = new Singleton();
	private Singleton(){
	
	}
	public static Singleton getInstance(){
		return singleton;
	}
Copy after login

Summary:

Lazy Man style: instantiate objects only when needed. In development, if the memory requirements are high, that is Using the lazy style, in a multi-threaded environment, you should use the DCL singleton mode. Using the DCL singleton mode solves the problems of concurrency security and low performance. If you add the volatile keyword, it can also prevent NPE exceptions caused by instruction reordering.

Hungry Chinese style: The object has already been instantiated when the class is loaded. If the memory requirements are not high, use the Hungry Chinese style. It is simple, not error-prone, and does not have any concurrency security and performance issues.

The above is the detailed content of Detailed introduction to singleton pattern. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

One article to understand the singleton pattern in JavaScript One article to understand the singleton pattern in JavaScript Apr 25, 2023 pm 07:53 PM

The JS singleton pattern is a commonly used design pattern that ensures that a class has only one instance. This mode is mainly used to manage global variables to avoid naming conflicts and repeated loading. It can also reduce memory usage and improve code maintainability and scalability.

The application of singleton mode and factory mode in C++ function overloading and rewriting The application of singleton mode and factory mode in C++ function overloading and rewriting Apr 19, 2024 pm 05:06 PM

Singleton pattern: Provide singleton instances with different parameters through function overloading. Factory pattern: Create different types of objects through function rewriting to decouple the creation process from specific product classes.

Getting Started with PHP: Singleton Pattern Getting Started with PHP: Singleton Pattern May 20, 2023 am 08:13 AM

In software development, we often encounter situations where multiple objects need to access the same resource. In order to avoid resource conflicts and improve program efficiency, we can use design patterns. Among them, the singleton pattern is a commonly used way to create objects, which ensures that a class has only one instance and provides global access. This article will introduce how to use PHP to implement the singleton pattern and provide some best practice suggestions. 1. What is the singleton mode? The singleton mode is a commonly used way to create objects. Its characteristic is to ensure that a class has only one instance and provides

PHP Design Patterns: The Path to Code Excellence PHP Design Patterns: The Path to Code Excellence Feb 21, 2024 pm 05:30 PM

Introduction PHP design patterns are a set of proven solutions to common challenges in software development. By following these patterns, developers can create elegant, robust, and maintainable code. They help developers follow SOLID principles (single responsibility, open-closed, Liskov replacement, interface isolation and dependency inversion), thereby improving code readability, maintainability and scalability. Types of Design Patterns There are many different design patterns, each with its own unique purpose and advantages. Here are some of the most commonly used PHP design patterns: Singleton pattern: Ensures that a class has only one instance and provides a way to access this instance globally. Factory Pattern: Creates an object without specifying its exact class. It allows developers to conditionally

In PHP, what is the concept of singleton design pattern? In PHP, what is the concept of singleton design pattern? Aug 18, 2023 pm 02:25 PM

The Singleton pattern ensures that a class has only one instance and provides a global access point. It ensures that only one object is available and under control in the application. The Singleton pattern provides a way to access its unique object directly without instantiating the object of the class. Example<?php classdatabase{ publicstatic$connection; privatefunc

Thoughts on thread safety issues in singleton mode in PHP Thoughts on thread safety issues in singleton mode in PHP Oct 15, 2023 am 10:14 AM

Thinking about thread safety issues of singleton mode in PHP In PHP programming, singleton mode is a commonly used design pattern. It can ensure that a class has only one instance and provide a global access point to access this instance. However, when using the singleton pattern in a multi-threaded environment, thread safety issues need to be considered. The most basic implementation of the singleton pattern includes a private constructor, a private static variable, and a public static method. The specific code is as follows: classSingleton{pr

Extension and customization of singleton pattern in PHP framework Extension and customization of singleton pattern in PHP framework Oct 15, 2023 am 11:10 AM

Extension and customization of singleton mode in PHP framework [Introduction] Singleton mode is a common design pattern, which ensures that a class can only be instantiated once in the entire application. In PHP development, the singleton pattern is widely used, especially in the development and expansion of frameworks. This article will introduce how to extend and customize the singleton pattern in the PHP framework and provide specific code examples. [What is the singleton pattern] The singleton pattern means that a class can only have one object instance and provides a global access point for external use. In PHP development, pass

Application scenarios and thread safety processes of singleton mode in PHP distributed systems Application scenarios and thread safety processes of singleton mode in PHP distributed systems Oct 15, 2023 pm 04:48 PM

Application scenarios and thread safety processes of singleton mode in PHP distributed systems Introduction: With the rapid development of the Internet, distributed systems have become a hot topic in modern software development. In distributed systems, thread safety has always been an important issue. In PHP development, the singleton pattern is a commonly used design pattern, which can effectively solve the problems of resource sharing and thread safety. This article will focus on the application scenarios and thread safety processes of the singleton pattern in PHP distributed systems, and provide specific code examples. 1. Singleton mode

See all articles