单例模式

单例模式的应用场景:
  • 注册表对象
  • 日志对象
为什么要使用单例:
  • 防止资源使用过度
  • 程序运行结果出现不一致情况
为什么不使用全局变量,非要用单例模式呢:
  • 全局静态变量,在一开始程序就会进行创建,如果这个变量使用不到,消耗资源也太大,就会造成浪费
  • 单例模式能保证返回唯一的实例,并且在使用的时候才创建
什么是单例模式:

确保一个类只有一个实例,并且提供一个全局的访问点

错误写法:
 1 package com.singlePattern.obj;
 2 
 3 /**
 4  * @program: designPattern
 5  * @description: 单例对象
 6  * @author: Mr.Yang
 7  * @create: 2018-11-24 21:00
 8  **/
 9 public class Singleton {
10     private static Singleton singleton;
11 
12     private Singleton(){}
13 
14     public static synchronized Singleton getInstance(){
15         if(singleton==null){
16             singleton=new Singleton();
17         }
18         return singleton;
19     }
20 }
View Code
 
错误解析:

其实这样写是可以的,但是会影响效率。当一个实例创建之后,再次进行这个方法的调用,会进行加锁,然后返回这个实例

优化处理-1
利用JVM在加载这个类的时候,保证先创建这个对象的实例,当调用方法的时候,直接返回。
 1 package com.singlePattern.obj;
 2 
 3 /**
 4  * @program: designPattern
 5  * @description: 单例对象
 6  * @author: Mr.Yang
 7  * @create: 2018-11-24 21:00
 8  **/
 9 public class Singleton {
10     private static Singleton singleton = new Singleton();
11 
12     private Singleton(){}
13 
14     public static  Singleton getInstance(){
15         return singleton;
16     }
17 }
View Code
 

优化处理-2

双重检查加锁
 1 package com.singlePattern.obj;
 2 
 3 /**
 4  * @program: designPattern
 5  * @description: 单例对象
 6  * @author: Mr.Yang
 7  * @create: 2018-11-24 21:00
 8  **/
 9 public class Singleton {
10    /* private static Singleton singleton = new Singleton();
11 
12     private Singleton(){}
13 
14     public static  Singleton getInstance(){
15         return singleton;
16     }*/
17 
18     //volatile关键词保证,当singleton变量被初始化成对象实例时,多个线程正确的处理该变量
19     private volatile static Singleton singleton;
20 
21     private Singleton() {
22     }
23 
24     /**
25      * 这种方式保证只有第一次创建实例的时候,才能彻底走完这个方法
26      * 双重检查加锁在1.4或者更早的jdva版本中,jvm对于volatile关键字的实现会导致双重检查加锁
27      * 的实现。建议这个版本中的不要使用这个设计模式。
28      *
29      * @return
30      */
31     public static Singleton getInstance() {
32         if (singleton == null) {
33             synchronized (Singleton.class) {
34                 if (singleton == null) {
35                     singleton = new Singleton();
36                 }
37             }
38         }
39         return singleton;
40     }
41 }
View Code
 
 
相比于其他设计模式:

单例模式是比较容易理解的,写法相比其他模式来说,也比较简单。

转载于:https://www.cnblogs.com/yangxiaojie/p/10013817.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值