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; }
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; } }
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; } }
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; }
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!

JS 单例模式是一种常用的设计模式,它可以保证一个类只有一个实例。这种模式主要用于管理全局变量,避免命名冲突和重复加载,同时也可以减少内存占用,提高代码的可维护性和可扩展性。

单例模式:通过函数重载提供不同参数的单例实例。工厂模式:通过函数重写创建不同类型的对象,实现创建过程与具体产品类的解耦。

Singleton模式确保一个类只有一个实例,并提供了一个全局的访问点。它确保在应用程序中只有一个对象可用,并处于受控状态。Singleton模式提供了一种访问其唯一对象的方式,可以直接访问,而无需实例化类的对象。示例<?php classdatabase{ publicstatic$connection; privatefunc

在软件开发中,常常遇到多个对象需要访问同一个资源的情况。为了避免资源冲突以及提高程序的效率,我们可以使用设计模式。其中,单例模式是一种常用的创建对象的方式,即保证一个类只有一个实例,并提供全局访问。本文将为大家介绍如何使用PHP实现单例模式,并提供一些最佳实践的建议。一、什么是单例模式单例模式是一种常用的创建对象的方式,它的特点是保证一个类只有一个实例,并提

导言PHP设计模式是一组经过验证的解决方案,用于解决软件开发中常见的挑战。通过遵循这些模式,开发者可以创建优雅、健壮和可维护的代码。它们帮助开发者遵循SOLID原则(单一职责、开放-封闭、Liskov替换、接口隔离和依赖反转),从而提高代码的可读性、可维护性和可扩展性。设计模式的类型有许多不同的设计模式,每种模式都有其独特的目的和优点。以下是一些最常用的php设计模式:单例模式:确保一个类只有一个实例,并提供一种全局访问此实例的方法。工厂模式:创建一个对象,而不指定其确切类。它允许开发者根据条件

单例模式在PHP分布式系统中的应用场景和线程安全流程引言:随着互联网的迅猛发展,分布式系统已成为现代软件开发的热门话题。而在分布式系统中,线程安全一直是一个重要的问题。在PHP开发中,单例模式是一种常用的设计模式,它可以有效地解决资源共享和线程安全的问题。本文将重点讨论单例模式在PHP分布式系统中的应用场景和线程安全流程,并提供具体的代码示例。一、单例模式的

单例模式在PHP中的常见应用场景剖析概述:单例模式(SingletonPattern)是一种创建型设计模式,它确保一个类只有一个实例,并提供一个全局访问点来访问该实例。在PHP中,使用单例模式可以有效地限制类的实例化次数和资源占用,提高代码的性能和可维护性。本文将通过分析常见的应用场景,给出具体的PHP代码示例,来说明单例模式的使用方法和好处。数据库连接管

设计模式中的单例模式与PHP中的应用引言:设计模式是在软件设计过程中,经验丰富的软件工程师总结出来的一些解决特定问题的经典模式。其中,单例模式是最常用的设计模式之一。单例模式确保一个类只有一个实例,并提供了一个全局访问点来访问这个实例。在PHP中,单例模式被广泛应用于各种场景。本文将详细介绍单例模式的概念、特点以及在PHP中的具体应用,同时给出相关的代码示例


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Chinese version
Chinese version, very easy to use

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)
