标签:Singleton E8% -- private static 设计模式 public
当系统中只需要一个实例或者一个全局访问点的时候可以使用单例模式。
-
优点:节省系统创建对象的资源,提高了系统效率,提供了统一的访问入口,可以严格控制用户对该对象的访问。
-
缺点:只有一个对象,积累的职责过重,违背了单一职责原则。构造方法为private,无法继承,扩展性较差。
懒汉式单例
public class Singleton {
private static Singleton instance;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
双层校验锁单例
public class Singleton {
private static volatile Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if(instance ==null){
instance = new Singleton();
}
}
}
return instance;
}
}
容器单例(饿汉模式)
public class Singleton {
private final static Singleton INSTANCE= new Singleton();
private Singleton() {
}
public static Singleton getInstance(){
return INSTANCE;
}
}
静态内部类单例
public class Singleton {
private Singleton() {
}
private static class SingletonInstance {
private final static Singleton INSTANCE = new Singleton();
}
public static Singleton5 getInstance() {
return SingletonInstance.INSTANCE;
}
}
枚举单例
public enum Singleton {
INSTANCE;
}
根据以下文章总结:
-
Java设计模式:23种设计模式全面解析(超级详细)HYPERLINK http://c.biancheng.net/design_pattern/ n委派模式在JDK以及Spring源码中的应用_蒙奇D灬小武的博客-CSDN博客
-
设计模式 https://blog.csdn.net/shusheng0007/category_8638565.html 永不磨灭的设计模式(有这一篇真够了,拒绝标题党)_ShuSheng007的博客-CSDN博客_永不磨灭的设计模式
-
java设计模式 https://blog.csdn.net/qq_37909508/category_8976362.html
-
设计模式 在源码中的应用 https://blog.csdn.net/qq_36970993/category_10620886.html
-
Android系统设计中存在设计模式分析 https://www.2cto.com/kf/201208/150650.html
-
Android设计模式系列 - 基于android的各种代码分析各种设计模式 https://www.cnblogs.com/qianxudetianxia/category/312863.html
标签:Singleton,E8%,--,private,static,设计模式,public 来源: https://blog.csdn.net/scoryy/article/details/123636803
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。