当前位置:网站首页>Singleton mode 3-- singleton mode
Singleton mode 3-- singleton mode
2022-07-25 15:25:00 【Literary youth learn programming】
What is a single example
Ensure that a class has only one instance , And provide an access to the global access point
Advantages and disadvantages of single case
advantage :
1. In singleton mode , Single instance of an activity has only one instance , All instantiations of a singleton class result in the same instance . So you Prevent other objects from instantiating themselves , Ensure that all objects access an instance
2. The singleton mode has certain scalability , Class to control the instantiation process , Class has corresponding scalability in changing the instantiation process .
3. Provides controlled access to unique instances .
4. Because there is only one object in system memory , So you can Save system resources , When The singleton mode can improve the performance of the system when objects need to be created and destroyed frequently .
5. Allows a variable number of instances .
6. Avoid multiple use of shared resources .
shortcoming :
1. Not applicable to changed objects , If objects of the same type always change in different use case scenarios , Single instance will cause data error , Can't save each other's states .
2. Because there is no abstraction layer in the simple interest model , Therefore, the extension of singleton classes is very difficult .
3. Singleton classes are overloaded , To a certain extent “ Principle of single responsibility ”.
4. Abuse of single case will bring some negative problems , For example, in order to save resources, the database connection pool object is designed as a single instance class , May cause too many programs sharing connection pool objects to overflow connection pool ; If the instantiated object is not used for a long time , The system will be recycled as garbage , This will result in the loss of object state .
How to create a single instance
- Hungry Chinese style : Class initialization , The object will be loaded immediately , Threads are inherently safe , High call efficiency .
- Slacker type : Class initialization , The object will not be initialized , This object is only created when it really needs to be used , Lazy loading function .
- Static internal way : It combines the advantages of lazy and hungry , Only when the object is really needed can it be loaded , Loading classes is thread safe .
- Enumerate singletons : Use enumeration to implement singleton pattern advantage : Implement a simple 、 High call efficiency , Enumeration itself is a singleton , from jvm Fundamental guarantee ! Avoid loopholes through reflection and deserialization , Disadvantages no delay in loading .
- Double detection lock mode ( because JVM The reason for the essential reordering , May be initialized multiple times , It is not recommended to use )
Hungry Chinese style
// Hungry Chinese style public class SingletonDemo01 { // Class initialization , The object will be loaded immediately , Threads are inherently safe , High call efficiency private static SingletonDemo01 singletonDemo01 = newSingletonDemo01();
private SingletonDemo01() { System.out.println("SingletonDemo01 initialization "); }
public static SingletonDemo01 getInstance() { System.out.println("getInstance"); return singletonDemo01; }
public static void main(String[] args) { SingletonDemo01 s1 = SingletonDemo01.getInstance(); SingletonDemo01 s2 = SingletonDemo01.getInstance(); System.out.println(s1 == s2); }
}
|
Slacker type
// Slacker type public class SingletonDemo02 {
// Class initialization , The object will not be initialized , This object is only created when it really needs to be used . private staticSingletonDemo02 singletonDemo02;
private SingletonDemo02() {
}
public synchronized staticSingletonDemo02 getInstance() { if (singletonDemo02 == null) { singletonDemo02 = new SingletonDemo02(); } return singletonDemo02; }
public static voidmain(String[] args) { SingletonDemo02 s1 = SingletonDemo02.getInstance(); SingletonDemo02 s2 = SingletonDemo02.getInstance(); System.out.println(s1 == s2); }
}
|
Static inner class
// Static inner class mode public class SingletonDemo03 { private SingletonDemo03() { System.out.println(" initialization .."); }
public static class SingletonClassInstance { private static final SingletonDemo03 singletonDemo03 = newSingletonDemo03(); }
// Method is not synchronized public static SingletonDemo03 getInstance() { System.out.println("getInstance"); returnSingletonClassInstance.singletonDemo03; }
public static void main(String[] args) { SingletonDemo03 s1 = SingletonDemo03.getInstance(); SingletonDemo03 s2 = SingletonDemo03.getInstance(); System.out.println(s1 == s2); } } |
advantage : Taking into account the lazy mode of memory optimization ( Initialization only when used ) And the safety of the hungry man model ( It won't be invaded by reflection ).
Inferiority : Two classes are needed to do this , It doesn't create objects of static inner classes , But its Class Objects will still be created , And it's a permanent object .
Enumeration method
What is enumeration
Enumeration itself is singleton , Commonly used in projects to define constants .
enum UserEnum { HTTP_200(200, " The request is successful "),HTTP_500(500," request was aborted "); private Integer code; private String name;
UserEnum(Integer code, String name) { this.code = code; this.name = name; }
public Integer getCode() { return code; }
public void setCode(Integer code) { this.code = code; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
public class TestEnum {
public static void main(String[] args) { System.out.println(UserEnum.HTTP_500.getCode()); }
} |
/ Use enumeration to implement singleton pattern advantage : Implement a simple 、 Enumeration itself is a singleton , from jvm Fundamental guarantee ! Avoid loopholes through reflection and deserialization Disadvantages no delay in loading public class User { public static User getInstance() { returnSingletonDemo04.INSTANCE.getInstance(); }
private static enum SingletonDemo04 { INSTANCE; // Enumeration elements are singletons private User user;
private SingletonDemo04() { System.out.println("SingletonDemo04"); user = new User(); }
public User getInstance() { return user; } }
public static void main(String[] args) { User u1 = User.getInstance(); User u2 = User.getInstance(); System.out.println(u1 == u2); } }
|
Double detection lock
public classSingletonDemo04 { privateSingletonDemo04 singletonDemo04;
privateSingletonDemo04() {
}
publicSingletonDemo04 getInstance() { if(singletonDemo04== null) { synchronized (this) { if(singletonDemo04== null) { singletonDemo04 = newSingletonDemo04(); } } } returnsingletonDemo04; }
} |
Single example to prevent reflection vulnerability attack
In the constructor , Only one initialization can be allowed .
private static booleanflag = false;
privateSingletonDemo04() {
if (flag == false) { flag = !flag; } else { throw newRuntimeException(" The singleton pattern is violated !"); } }
public static voidmain(String[] args) {
} |
How to choose a single instance creation method
If you don't need to delay loading the singleton , You can use enumeration or starvation , Comparatively speaking, enumeration is better than starvation .
If you need to delay loading , You can use static inner classes or lazy Korean , Relatively speaking, static inner class is better than lazy Korean .
边栏推荐
- BPSK调制系统MATLAB仿真实现(1)
- 打开虚拟机时出现VMware Workstation 未能启动 VMware Authorization Service
- Instance tunnel use
- C语言函数复习(传值传址【二分查找】,递归【阶乘,汉诺塔等】)
- Vscode plugin collection
- Spark002 --- spark task submission, pass JSON as a parameter
- Reflection - Notes
- Simulate setinterval timer with setTimeout
- Xcode添加mobileprovision证书文件报错:Xcode encountered an error
- 《三子棋》C语言数组应用 --n皇后问题雏形
猜你喜欢

Spark memory management mechanism new version

Spark AQE

图论及概念

ML - 语音 - 语音处理介绍

outline和box-shadow实现外轮廓圆角高光效果

Distributed principle - what is a distributed system

Yan required executor memory is above the max threshold (8192mb) of this cluster!

MATLAB读取显示图像时数据格式转换原因

ML - 图像 - 深度学习和卷积神经网络

ML - 自然语言处理 - 自然语言处理简介
随机推荐
异步fifo的实现
海缆探测仪TSS350(一)
How spark gets columns in dataframe --column, $, column, apply
vscode 插件篇收集
ML - 语音 - 传统语音模型
伤透脑筋的CPU 上下文切换
本地缓存--Ehcache
Debounce and throttle
Endnote 无法编辑range 解决
HBCK fix problem
记一次Yarn Required executor memeory is above the max threshold(8192MB) of this cluster!
How to solve the problem of scanf compilation error in Visual Studio
记一次Spark报错:Failed to allocate a page (67108864 bytes), try again.
CGO is realy Cool!
args参数解析
CGO is realy Cool!
Promise object and macro task, micro task
图论及概念
我的创作纪念日
数据系统分区设计 - 分区再平衡(rebalancing)