当前位置:网站首页>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 .
边栏推荐
- Promise对象与宏任务、微任务
- JVM-参数配置详解
- Delayed loading source code analysis:
- 如何解决Visual Studio中scanf编译报错的问题
- matlab---错误使用 var 数据类型无效。第一个输入参数必须为单精度值或双精度值
- ML - 语音 - 语音处理介绍
- 记一次Spark报错:Failed to allocate a page (67108864 bytes), try again.
- 看到很多App出现闪烁的图片,特别是会员页面
- MySql的安装配置超详细教程与简单的建库建表方法
- ML - Speech - advanced speech model
猜你喜欢

Debounce and throttle

《三子棋》C语言数组应用 --n皇后问题雏形

What is the Internet of things

Image cropper example

Spark SQL空值Null,NaN判断和处理

图片裁剪cropper 示例

How to solve the problem of scanf compilation error in Visual Studio

MySql的安装配置超详细教程与简单的建库建表方法

NPM's nexus private server e401 E500 error handling record

如何解决Visual Stuido2019 30天体验期过后的登陆问题
随机推荐
Maxcompute SQL 的查询结果条数受限1W
Vscode plugin collection
Xcode添加mobileprovision证书文件报错:Xcode encountered an error
Tasks, micro tasks, queues and scheduling (animation shows each step of the call)
CGO is realy Cool!
ML - natural language processing - Introduction to natural language processing
记一次Spark foreachPartition导致OOM
Docker上运行redis以配置文件方式启动,连接客户端报错Error: Server closed the connection
如何更新更新数据库中的json值?
RedisCluster搭建和扩容
MySQL heap table_ MySQL memory table heap Usage Summary - Ninth Five Year Plan small pang
Introduction to raspberry Pie: initial settings of raspberry pie
Reflection - Notes
redis淘汰策列
JVM parameter configuration details
苹果内购和Apple Pay 的区别
How to solve the problem of scanf compilation error in Visual Studio
任务、微任务、队列和调度(动画展示每一步调用)
Instance Tunnel 使用
期货在线开户是否安全?去哪家公司手续费最低?