当前位置:网站首页>Singleton mode
Singleton mode
2022-07-26 16:32:00 【Old [email protected]】
Classification of design patterns
Create pattern
The singleton pattern 、 Abstract factory pattern 、 Archetypal model 、 Builder pattern 、 Factory mode
Structural mode
Adapter pattern 、 Bridging mode 、 Decoration mode 、 Portfolio model 、 Appearance mode 、 The flyweight pattern 、 The proxy pattern
Behavioral patterns
Template method pattern 、 Command mode 、 Visitor mode 、 Iterator pattern 、 Observer mode 、 Intermediary model 、 Memo mode 、 Interpreter mode 、 The state pattern 、 The strategy pattern 、 Responsibility chain pattern
The singleton pattern
Introduction to single mode
The so-called singleton pattern , Is to take certain methods to ensure that in the whole software system , There can only be one object instance for a class , And this class only provides a method to get its object instance ; for example Hibernate Of SessionFactory, It acts as a proxy for the data source , And responsible for creating Session object ,SessionFactory It's not lightweight , In general , A project usually only needs one SessionFactory object
Hungry Chinese style ( static const )
/*** * @author shaofan * @Description A single case of hungry Han style , Static variables */
public class Hungry1 {
/** * Privatized constructor , Way to create objects outside */
private Hungry1(){
}
/** * Use static constants to create objects , Rely on class loading mechanism , Static variables are loaded only once during class initialization , So the created object is singleton */
private final static Hungry1 INSTANCE = new Hungry1();
/** * Get instance * @return */
public Hungry1 getInstance(){
return INSTANCE;
}
}
Advantages and disadvantages
- advantage : Written in simple , It is to complete instantiation during class loading through class loading mechanism , Avoid thread synchronization problems
- shortcoming : Instantiate when the class is installed , No lazy loading effect , If you have never used this instance from the beginning to the end , Memory is wasted
- This way is based on classloader The mechanism avoids the synchronization problem of multithreading , however ,instance When the class is loaded, it is pear blossom , In singleton mode, most of them call getInstance Method , But there are many reasons for class loading , So it's not certain there are other ways ( Or other static methods ) Causes the class to load , There is no need to use instance But initialize instance It does not achieve the effect of lazy loading
- This singleton mode is available , May cause memory waste ( You can use it if you promise to use it )
Hungry Chinese style ( Static code block )
/*** * @author shaofan * @Description Hungry Chinese style , Static code block */
public class Hungry2 {
private static Hungry2 instance;
/** * Privatized constructor , Prevent external new object */
private Hungry2(){
}
// Initialize the instance in a static code block
static {
instance =new Hungry2();
}
/** * Get instance * @return */
public static Hungry2 getINSTANCE() {
return instance;
}
}
Advantages and disadvantages
This method is the same as that of static variables , All use the class loading mechanism to complete the initialization of instances
Slacker type ( Thread unsafe )
/*** * @author shaofan * @Description Slacker type , Thread unsafe */
public class Lazy1 {
private static Lazy1 instance;
private Lazy1(){
}
/** * obtain instance First judge whether it is empty , If it is empty, create , If it is not empty, return ; But in a multithreaded environment , Multiple threads may be detected as null at the same time , Causes duplicate creation of * @return */
public static Lazy1 getInstance(){
if(instance==null){
instance = new Lazy1();
}
return instance;
}
}
Advantages and disadvantages
- It has the effect of lazy loading , But it can only be used in single thread
- If it's multithreaded , A thread has entered if Judgment block , There is no time to carry it out , Another thread also passed this judgment statement , This is the time to generate multiple instances
- In development , This method is not recommended
Slacker type ( Synchronization method )
/*** * @author shaofan * @Description Slacker type , Synchronization method */
public class Lazy2 {
private static Lazy2 instance;
private Lazy2(){
}
/** * Use synchronized Keyword synchronization getInstance Method , Ensure that only one thread enters this method at the same time , You won't create multiple instances * @return */
public static synchronized Lazy2 getInstance() {
if(instance==null){
instance = new Lazy2();
}
return instance;
}
}
Advantages and disadvantages
- advantage : Solved the thread unsafe problem
- shortcoming : Too inefficient , When each thread wants to get an instance of a class , perform getInstance() Methods should be synchronized . In fact, only one instantiation of this method is enough , Later, if you want to get an example directly return that will do ; Directly add synchronized Keyword will cause every call to be locked , Low efficiency
- In actual development , It is not recommended to use
Double check
/*** * @author shaofan * @Description Slacker type , Double check */
public class Lazy3 {
private static Lazy3 instance;
private Lazy3(){
}
/** * Synchronize code blocks through class locks , Multiple threads are aligned first instance Make null value judgment , Conduct the first round of inspection , A small number of threads will enter during the first creation , Only lock the thread when it is first created , Carry out the second level inspection * @return */
public Lazy3 getInstance(){
if(instance==null){
synchronized (Lazy3.class){
if(instance==null){
instance = new Lazy3();
}
}
}
return instance;
}
}
Advantages and disadvantages
- Double-Check The concept is often used in multithreaded development , As shown in the code , Two null value checks were performed , It will be locked the second time , This improves performance while ensuring thread safety
- Thread safety 、 Delay loading 、 More efficient
- In actual development , Recommended
Static inner class
/*** * @author shaofan * @Description Static inner class mode */
public class StaticInner {
private StaticInner(){
}
/*** * Static inner classes are not loaded when outer classes are loaded , Instead, it has its own startup and loading mechanism , Load when calling this class for the first time , It will also have the effect of lazy loading , At the same time, due to the single load characteristics of the class , * The examples are also single */
private static class Instance{
private static final StaticInner INSTANCE = new StaticInner();
}
public StaticInner getInstance(){
return Instance.INSTANCE;
}
}
Advantages and disadvantages
- This method uses the class loading mechanism to ensure that the initialization instance has only one thread
- The static internal class method will not be instantiated immediately when the external class is loaded , But when you need to instantiate , call getInstance Method , To load the inner class , To complete the instantiation
- The static properties of a class are initialized only when the class is first loaded , So here ,JVM Help us ensure thread safety , There will be no multiple threads initializing the class multiple times
- advantage : Thread safety , Using static inner classes to achieve delayed loading , Efficient
- Recommended
enumeration
/*** * @author shaofan * @Description Enumeration method */
public enum Singleton {
INSTANCE;
}
Advantages and disadvantages
- With the help of jdk1.5 Add enumeration to implement singleton mode , It can not only avoid threading problems , It also prevents deserialization from recreating new objects
- This way is still Effective Java The way the author advocates
- Recommended
Singleton pattern source code analysis
stay JDK in ,java.lang.Runtime The singleton mode is used 
Here we use the starving Han style singleton mode
summary
- Singleton mode ensures that there is only one object in the system memory , Save system resources , For some objects that need to be destroyed by frequently disassembling function keys , Using singleton mode can improve system performance
- When you need to instantiate a singleton class , You must use the corresponding method of obtaining instances , instead of new
- Scenario used in singleton mode : Objects that need to be created and destroyed frequently 、 Creating objects takes too much time or resources ( Heavyweight objects ), But also commonly used objects 、 Utility class object 、 Objects that frequently access databases or files ( For example, data source 、session The factory etc. )
版权声明
本文为[Old [email protected]]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/207/202207261514178887.html
边栏推荐
- Re7:读论文 FLA/MLAC Learning to Predict Charges for Criminal Cases with Legal Basis
- Pat class a 1047 student list for course
- Application of workflow engine in vivo marketing automation
- 国元期货网上开户安全吗?开户办理流程是怎样的?
- 综合设计一个OPPE主页--明星机型的设计
- Comprehensively design an oppe homepage -- the design of the top and head
- 匿名方法和lambda表达式使用的区别
- Linux安装mysql8.0.29详细教程
- Clojure Web Development -- ring user guide
- vlang捣鼓之路
猜你喜欢
![[arm learning (9) ARM compiler understanding learning (armcc/armclang)]](/img/6c/df2ebb3e39d1e47b8dd74cfdddbb06.gif)
[arm learning (9) ARM compiler understanding learning (armcc/armclang)]

Botu PLC Sequential switch function block (SCL)

Comprehensively design an oppe homepage -- layout and initialization

研发效能的道与术 - 道篇

测试用例千万不能随便,记录由一个测试用例异常引起的思考

Guetzli simple to use

Simulation of three-phase voltage source inverter based on SISOTOOL pole assignment PI parameters and pless

基于sisotool极点配置PI参数及基于Plecs的三相电压源逆变器仿真
Final consistency distributed transaction TCC

Nacos win10 安装配置教程
随机推荐
DTS is equipped with a new self-developed kernel, which breaks through the key technology of the three center architecture of the two places Tencent cloud database
Question collection come and ask nllb authors! (Zhiyuan live issue 24)
ZABBIX 6.2.0 deployment
Wechat applet - network data request
VS2017打开项目提示需要迁移的解决方法
What is GPIO and what is its use
【Flutter -- 进阶】打包
修改mysql数据库root用户的密码
C # method to read the text content of all files in the local folder
我的sql没问题为什么还是这么慢|MySQL加锁规则
NUC 11 build esxi 7.0.3f install network card driver-v2 (upgraded version in July 2022)
Tao and art of R & D Efficiency - Tao chapter
Pat grade a 1050 string subtraction
Docker install redis? How to configure persistence policy?
Bugku login1
工作流引擎在vivo营销自动化中的应用实践
vlang捣鼓之路
kubernetes之探针
综合设计一个OPPE主页--明星机型的设计
Test cases should never be used casually, recording the thinking caused by the exception of a test case