Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the use of singleton pattern in Java design pattern

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Editor to share with you what is the use of singleton patterns in Java design patterns. I hope you will gain something after reading this article. Let's discuss it together.

Define

Singleton mode ensures that there is only one instance of a class and provides a global access point.

Implementation of Java Singleton pattern Classical Singleton pattern public class Singleton {private static Singleton uniqueInstance / / use a static variable to record the unique instance of the Singleton class private Singleton () {} / / declare the constructor private only from within the Singleton class / / instantiate the object with the getInstance () method and return the instance public static Singleton getInstance () {if (uniqueInstance = = null) {uniqueInstance = new Singleton () } return uniqueInstance;}}

The above code generates multiple instances in multithreading, so we need to improve the code.

Implementation of multithreaded singleton public class Singleton {private static Singleton uniqueInstance; private Singleton () {} public static synchronized Singleton getInstance () {if (uniqueInstance = = null) {uniqueInstance = new Singleton ();} return uniqueInstance;}}

By adding the synchronized keyword to the getInstance () method, we force each thread to wait for another thread to leave the method before entering the method. That is, no two threads can enter this method at the same time.

Eager to create an instance public class Singleton {/ / create a singleton in a static initializer (static initializai). This ensures thread safety (thread sate) private static Singleton uniqueInstance = new Singleton (); private static Singleton getInstance () {return uniqueInstance;}}

Create this unique singleton instance as soon as JVM loads the class. JVM guarantees that this instance will be created before any thread accesses the uniqueInstance static variable.

Double check lock

It will check whether the instance exists twice, create it if it does not exist, and return if it does

Public class Singlenton {/ / volatile keywords: when the uniqueInstance variable is initialized to a Singleton instance, multiple threads correctly handle the uniqueInstance variable private volatile static Singleton uniqueInstance () Private Singleton () {} public static Singleton getInstance () {/ / check the instance. If it does not exist, enter the synchronization block if (uniqueInstance = = null) {/ / and check again. If it is still null, create the instance synchronized (Singleton.class) {if (uniqueInstance = = null) {uniqueInstance = new Singleton ();} return uniqueInstance }} Python singleton mode module implementation

The module of Python is a natural singleton mode. When the module is imported for the first time, a .pyc file is generated. When it is imported again, the previously generated .pyc file is loaded directly, and the module code is not executed again.

Create a Singleton file first

Class Singleton: def getSingleton: passsingleton = Singleton ()

Import this module in other files, and the address of this class is unique

New keyword implementation

When instantiating an object, the _ _ new__ method of the class is called first, and the parent class Object.__new__ method is called by default to instantiate the object. The _ _ init__ method of the class is then called to initialize the property.

We can add a judgment to the _ _ new__ method: if the instance exists, it is not instantiated; if it does not exist, it is instantiated.

Class Singleton (object): _ instance = None def _ _ new__ (cls, * args, * * kwargs): if cls._instance is None: cls._instance = object.__new__ (cls, * args, * * kwargs) return cls._instance def _ init__ (self): pass decorator implementation

Implement the singleton pattern through the decorator

Function decorator def singleton (cls): # create a private variable of type dictionary _ instance = {} def inner (): # if the class does not exist if cls not in _ instance: # instantiate a class and store it in the dictionary _ instance[ CLS] = cls () return _ instance[ CLS] return inner @ singletonclass ClassName (object): def _ init__ (self): Pass class decorator class Singleton (object): def _ _ init__ (self Cls): self._cls = cls # accept the class name self._instance = {} # store the class address def _ _ call__ (self): if self._cls not in self._instance: # instantiate the class and store it in the dictionary self._ instance [self. _ cls] = self._cls () return self._instance [ Self._cls] @ Singletonclass ClassName (object): def _ _ init__ (self): pass has finished reading this article I believe you have a certain understanding of "what is the use of singleton patterns in Java design patterns". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report