Android 设计模式——————单列模式——————简单的单列模式在项目中的运用

一、恶汉式

/**
 * Created by yanbo on 2017/7/7.
 * 恶汉试(类加载就初始化)
 */
public class Singleton {
    public static Singleton instance = new Singleton();
    //提供外界访问的方法
    public static Singleton getInstance(){
        return instance;
    }
}

二、懒汉式

/**
 * Created by yanbo on 2017/7/7.
 * 懒汉式(双重判断)
 */

public class Singleton2 {
    public static Singleton2 instance;
    public static Singleton2 getInstance(){
        if (instance == null){//判断
            synchronized (Singleton2.class){
                if (instance == null){
                    instance = new Singleton2();
                }
            }
        }
        return instance;
    }
}

三、使用Java的枚举

    public enum Singleton03  
    {  
        INSTANCE;  
    }  

四、使用一个持有类,主要是为了不在初始化的时候加载

public class Singleton04  
{  
    private static final class InstanceHolder  
    {  
        private static Singleton04 INSTANCE = new Singleton04();  
    }  

    public static Singleton04 getInstance()  
    {  
        return InstanceHolder.INSTANCE;  
    }  
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值