设计模式之二: 单例模式

单例模式是工作中经常用的一种设计模式, 其主要用于设计程序中公共使用的部分, 下面是三种常用常见的三个写法:

第一种: 线程安全不懒汉模式

public class Singleton {
    private static Singleton instance;
    private Singleton (){}

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}  

优点:  容易理解单例模式,适用于单线程程序.

缺点: 线程不安全(比如某个线程A 判断if(intstance == null) 后该任务时间片到了,操作系统做别的事情后 再回来就会直接new 新的实例, 而此时, 可能已经有新的实例了),容易出现new 出多个实例的情况,不适用于多线程程序.

第二种: 线程安全的懒汉模式

public class FirstInstanceAlgori {
    private static FirstInstanceAlgori mInstance;
    private FirstInstanceAlgori(){
    }
    public static FirstInstanceAlgori getInstance() {
        synchronized (FirstInstanceAlgori.class){
            if (mInstance == null){
                mInstance = new FirstInstanceAlgori();
            }
            return mInstance;
        }
    }
}

优点:  基于第二种得来, 解决了第一种的线程安全问题, 多线程中可以正常运行.

缺点:  效率比较低(因为无论单例是否被创建, 都给对象加锁了,)

第三种: 双重检验锁单例模式

    public static int initialValue = 100;
    private static FirstInstanceAlgori mInstance;
    private FirstInstanceAlgori(){
    }

    public static FirstInstanceAlgori getInstance() {
        if (mInstance == null) {
            synchronized (FirstInstanceAlgori.class){
                if (mInstance == null){
                    mInstance = new FirstInstanceAlgori();
                }
                return mInstance;
            }
        }
    }
}

优点: 基于第二种得来, 线程安全, 效率提高了.

缺点: 后面补充,

      需要理解单例设计模式的设计思想, 这样在实际写代码的过程中,  才能比较有底.

     个人是这么理解的:

1. 类的构造函数要是私有.

     在代码中,单例模式作用的对象是类, 类的构造函数是不能被外面的对象调用的(不然是实现不了单例).

2. 对外接口必须是静态的.

    为了供外部调用, 又不能被外部创建对象(调用类中方法有两种方法,

    (1)创建对象,直接调用,new Person().function().

     (2) 用.静态方法才能这样  ). 所以只能选第二种.

3. 声明单例变量的时候要是静态.

    因为对外接口是静态的, 静态方法只能访问静态的成员变量. (因为静态函数的生命周期更长, 编译的时候就占空间,此时非静态变量还没有生出来).


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值