Home Java javaTutorial A brief discussion on several common design patterns in Java: singleton pattern

A brief discussion on several common design patterns in Java: singleton pattern

Jul 23, 2018 am 11:25 AM
java design patterns

1. Singleton pattern

It is one of the more commonly used design patterns in Java. Its core structure only contains a special class called a singleton. The singleton pattern can ensure that there is only one instance of the class that applies this pattern in the system.

2. Pattern requirements

1. Your own construction method must be privatized

2. Create your own unique instance inside the class

3 , provide a public static method for other objects to obtain the instance

3. Several implementation methods

hunger style

public class Simple {
private static Simple simple = new Simple();
private Simple() {
}
public static Simple getInstance() {
return simple;
}
}

This implementation method is used when the class is loaded Instantiation is done without lazy loading and is thread safe.

Lazy Man Style

public class Slacker {
private static volatile Slacker slacker = null;
private Slacker() {
}
/**
* 最简单的懒汉式实现
* @return
*/
public static Slacker getInstance() {
if(slacker == null) {
slacker = new Slacker();
}
return slacker;
}
}

This implementation is the most basic implementation. The biggest problem is that it does not support multi-threading. The concurrent access method will obtain more than one instance, so strictly speaking it is not a singleton. model.

public class Slacker {
//volatile关键字的作用
//1、保证内存可见性:保证每个线程访问volatile修饰的共享变量时获取到的都是最新的。
//2、防止指令重排序--通过内存屏障实现
private static volatile Slacker slacker = null;
private Slacker() {
}
/**
* 加synchronized关键字解决线程同步问题
* @return
*/
public static synchronized Slacker getInstanceSync() {
if(slacker == null) {
slacker = new Slacker();
}
return slacker;
}
}

This method of adding synchronized locks to methods can solve the problem of concurrent access by threads and implement singletons. However, adding locks will affect efficiency, so it is often not used this way.

Double check lock

public class Slacker {
//volatile关键字的作用
//1、保证内存可见性:保证每个线程访问volatile修饰的共享变量时获取到的都是最新的。
//2、防止指令重排序--通过内存屏障实现
private static volatile Slacker slacker = null;
private Slacker() {
}
/**
* 双重检查锁解决线程同步问题
* @return
*/
public static Slacker getInstanceDoubleLock() {
if(slacker == null) {
synchronized (Slacker.class) {
if(slacker == null) {
slacker = new Slacker();
}
}
}
return slacker;
}
}

This method uses a double lock mechanism, which can adapt to multi-threaded concurrent access and maintain high performance.

Static inner class implementation

/**
* 静态内部类方式实现单例模式
*
* 当StaticInnerClass第一次被加载时,并不需要去加载StaticInnerClassHoler,只有当getInstance()方法第一次被调用时,
* 才会去初始化staticInnerClass,第一次调用getInstance()方法会导致虚拟机加载StaticInnerClassHoler类,这种方法不仅能
* 确保线程安全,也能保证单例的唯一性,同时也延迟了单例的实例化。
*
* @author chenf
*
*/
public class StaticInnerClass {
private StaticInnerClass() {
}
// 静态内部类
private static class StaticInnerClassHoler {
// 在静态内部类中定义外部类的实例
private static StaticInnerClass staticInnerClass = new StaticInnerClass();
}
/**
* 获取时调用静态内部类的类属性获取外部类的实例
*
* @return
*/
public static StaticInnerClass getInstance() {
return StaticInnerClassHoler.staticInnerClass;
}
}

This method can not only achieve multi-threaded safe access, but also use the internal class loading mechanism to achieve lazy loading.

The above is the detailed content of A brief discussion on several common design patterns in Java: 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Hot Topics

PHP Tutorial
1511
276
Java Virtual Threads Performance Benchmarking Java Virtual Threads Performance Benchmarking Jul 21, 2025 am 03:17 AM

Virtual threads have significant performance advantages in highly concurrency and IO-intensive scenarios, but attention should be paid to the test methods and applicable scenarios. 1. Correct tests should simulate real business, especially IO blocking scenarios, and use tools such as JMH or Gatling to compare platform threads; 2. The throughput gap is obvious, and it can be several times to ten times higher than 100,000 concurrent requests, because it is lighter and efficient in scheduling; 3. During the test, it is necessary to avoid blindly pursuing high concurrency numbers, adapting to non-blocking IO models, and paying attention to monitoring indicators such as latency and GC; 4. In actual applications, it is suitable for web backend, asynchronous task processing and a large number of concurrent IO scenarios, while CPU-intensive tasks are still suitable for platform threads or ForkJoinPool.

how to set JAVA_HOME environment variable in windows how to set JAVA_HOME environment variable in windows Jul 18, 2025 am 04:05 AM

TosetJAVA_HOMEonWindows,firstlocatetheJDKinstallationpath(e.g.,C:\ProgramFiles\Java\jdk-17),thencreateasystemenvironmentvariablenamedJAVA_HOMEwiththatpath.Next,updatethePATHvariablebyadding%JAVA\_HOME%\bin,andverifythesetupusingjava-versionandjavac-v

How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Implement a linked list in Java Implement a linked list in Java Jul 20, 2025 am 03:31 AM

The key to implementing a linked list is to define node classes and implement basic operations. ①First create the Node class, including data and references to the next node; ② Then create the LinkedList class, implementing the insertion, deletion and printing functions; ③ Append method is used to add nodes at the tail; ④ printList method is used to output the content of the linked list; ⑤ deleteWithValue method is used to delete nodes with specified values and handle different situations of the head node and the intermediate node.

Java Microservices Service Mesh Integration Java Microservices Service Mesh Integration Jul 21, 2025 am 03:16 AM

ServiceMesh is an inevitable choice for the evolution of Java microservice architecture, and its core lies in decoupling network logic and business code. 1. ServiceMesh handles load balancing, fuse, monitoring and other functions through Sidecar agents to focus on business; 2. Istio Envoy is suitable for medium and large projects, and Linkerd is lighter and suitable for small-scale trials; 3. Java microservices should close Feign, Ribbon and other components and hand them over to Istiod for discovery and communication; 4. Ensure automatic injection of Sidecar during deployment, pay attention to traffic rules configuration, protocol compatibility, and log tracking system construction, and adopt incremental migration and pre-control monitoring planning.

Advanced Java Collection Framework Optimizations Advanced Java Collection Framework Optimizations Jul 20, 2025 am 03:48 AM

To improve the performance of Java collection framework, we can optimize from the following four points: 1. Choose the appropriate type according to the scenario, such as frequent random access to ArrayList, quick search to HashSet, and concurrentHashMap for concurrent environments; 2. Set capacity and load factors reasonably during initialization to reduce capacity expansion overhead, but avoid memory waste; 3. Use immutable sets (such as List.of()) to improve security and performance, suitable for constant or read-only data; 4. Prevent memory leaks, and use weak references or professional cache libraries to manage long-term survival sets. These details significantly affect program stability and efficiency.

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Building RESTful APIs in Java with Jakarta EE Building RESTful APIs in Java with Jakarta EE Jul 30, 2025 am 03:05 AM

SetupaMaven/GradleprojectwithJAX-RSdependencieslikeJersey;2.CreateaRESTresourceusingannotationssuchas@Pathand@GET;3.ConfiguretheapplicationviaApplicationsubclassorweb.xml;4.AddJacksonforJSONbindingbyincludingjersey-media-json-jackson;5.DeploytoaJakar

See all articles