您的位置:首页 > 移动开发 > Android开发

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

2017-07-07 17:26 183 查看

一、恶汉式

/**
* 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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: