Detailed explanation of examples of Java singleton pattern
This article mainly introduces the relevant information of detailed examples of java singleton mode. I hope that this article can help everyone thoroughly understand and master this part of the content. Friends in need can refer to
java singleton Detailed explanation of examples of example pattern
Concept:
The singleton pattern in java is a common design pattern. There are three types of singleton patterns. : There are three types: lazy man-style singleton, hungry man-style singleton, and registration-style singleton.
The singleton mode has the following characteristics:
1. A singleton class can only have one instance.
2. The singleton class must create its own unique instance.
3. The singleton class must provide this instance to all other objects.
The singleton pattern ensures that a class has only one instance, instantiates itself and provides this instance to the entire system. In computer systems, thread pools, caches, log objects, dialog boxes, printers, and graphics card driver objects are often designed as singletons. These applications all have more or less the functionality of resource managers. Each computer can have several printers, but there can only be one Printer Spooler to prevent two print jobs from being output to the printer at the same time. Each computer can have several communication ports, and the system should centrally manage these communication ports to prevent one communication port from being called by two requests at the same time. In short, the purpose of choosing the singleton mode is to avoid inconsistent states and avoid long-term policies.
First look at a classic singleton implementation.
public class Singleton { private static Singleton uniqueInstance = null; private Singleton() { // Exists only to defeat instantiation. } public static Singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } // Other methods... }
Singleton avoids the class from being instantiated externally by limiting the constructor to private. Within the scope of the same virtual machine, the only instance of Singleton can only pass getInstance( ) method access. (In fact, it is possible to instantiate a class with a private constructor through the Java reflection mechanism, which will basically invalidate all Java singleton implementations. This issue will not be discussed here. Let’s pretend that the reflection mechanism does not exist. .)
But the above implementation does not consider thread safety issues. The so-called thread safety means: if there are multiple threads running at the same time in the process where your code is located, these threads may run this code at the same time. If the results of each run are the same as those of single-threaded runs, and the values of other variables are the same as expected, it is thread-safe. In other words: the interface provided by a class or program is an atomic operation for threads or switching between multiple threads will not cause ambiguity in the execution results of the interface, which means that we do not need to consider synchronization issues. Obviously the above implementation does not meet the requirements of thread safety, and multiple Singleton instances are likely to appear in a concurrent environment.
public class TestStream { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } //该类只能有一个实例 private TestStream(){} //私有无参构造方法 //该类必须自行创建 //有2种方式 /*private static final TestStream ts=new TestStream();*/ private static TestStream ts1=null; //这个类必须自动向整个系统提供这个实例对象 public static TestStream getTest(){ if(ts1==null){ ts1=new TestStream(); } return ts1; } public void getInfo(){ System.out.println("output message "+name); } } /** * */ public class TestMain { public static void main(String [] args){ TestStream s=TestStream.getTest(); s.setName("张孝祥"); System.out.println(s.getName()); TestStream s1=TestStream.getTest(); s1.setName("张孝祥"); System.out.println(s1.getName()); s.getInfo(); s1.getInfo(); if(s==s1){ System.out.println("创建的是同一个实例"); }else if(s!=s1){ System.out.println("创建的不是同一个实例"); }else{ System.out.println("application error"); } } }
Run result:
张孝祥 张孝祥 output message 张孝祥 output message 张孝祥 创建的是同一个实例
Conclusion: From the result, we can know the singleton The pattern provides an object-oriented application with a unique access point to objects. No matter what function it implements, the entire application will share an instance object.
1. Hungry Chinese style singleton class
//饿汉式单例类.在类初始化时,已经自行实例化 public class Singleton1 { //私有的默认构造子 private Singleton1() {} //已经自行实例化 private static final Singleton1 single = new Singleton1(); //静态工厂方法 public static Singleton1 getInstance() { return single; } }
2. Lazy Chinese style singleton class
//懒汉式单例类.在第一次调用的时候实例化 public class Singleton2 { //私有的默认构造子 private Singleton2() {} //注意,这里没有final private static Singleton2 single=null; //静态工厂方法 public synchronized static Singleton2 getInstance() { if (single == null) { single = new Singleton2(); } return single; } }
3. Registration singleton class
import java.util.HashMap; import java.util.Map; //登记式单例类. //类似Spring里面的方法,将类名注册,下次从里面直接获取。 public class Singleton3 { private static Map<String,Singleton3> map = new HashMap<String,Singleton3>(); static{ Singleton3 single = new Singleton3(); map.put(single.getClass().getName(), single); } //保护的默认构造子 protected Singleton3(){} //静态工厂方法,返还此类惟一的实例 public static Singleton3 getInstance(String name) { if(name == null) { name = Singleton3.class.getName(); System.out.println("name == null"+"--->name="+name); } if(map.get(name) == null) { try { map.put(name, (Singleton3) Class.forName(name).newInstance()); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } return map.get(name); } //一个示意性的商业方法 public String about() { return "Hello, I am RegSingleton."; } public static void main(String[] args) { Singleton3 single3 = Singleton3.getInstance(null); System.out.println(single3.about()); } }
The above is the detailed content of Detailed explanation of examples of Java singleton pattern. For more information, please follow other related articles on the PHP Chinese website!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


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

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

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor