通知 网站从因情语写改为晴雨,这个网站的模板也从calmlog_ex改为 whimurmur

创建型模式-单例模式

3148人浏览 / 0人评论 / | 作者:因情语写  | 分类: 设计模式与算法  | 标签: 设计模式与算法  | 

作者:因情语写

链接:https://www.proprogrammar.com/article/440

声明:请尊重原作者的劳动,如需转载请注明出处


  单例的实现有多种,有懒汉模式,饿汉模式,枚举方式,静态内部类方式等等,下面说说上面的四种

  懒汉模式:加载类时就初始化单例

package creational.pattern.singleton;

public class HungrySingleton {
    // 类初始化时获得实例
    private static HungrySingleton INSTANCE = new HungrySingleton();;
    
    // 私有化构造器,只能通过getInstance方法获得单例
    private HungrySingleton(){}
    
    // 获取单例实例
    public static HungrySingleton getInstance()
    {
        return INSTANCE;
    }
}

  饿汉模式(双重校验锁)

package creational.pattern.singleton;

import java.io.Serializable;

/*
 * jdk 1.5 后可以保证多线程下的安全
 */
public class DoubleCheckedLockingSingleton implements Serializable {
    
    private static final long serialVersionUID = -1926737179243132977L;
    
    private static DoubleCheckedLockingSingleton INSTANCE;

    private DoubleCheckedLockingSingleton() {
    }

    public static DoubleCheckedLockingSingleton getInstance() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        if (null == INSTANCE) {
            synchronized (DoubleCheckedLockingSingleton.class) {
                if (null == INSTANCE)
                    INSTANCE = (DoubleCheckedLockingSingleton) getClass("creational.pattern.singleton.DoubleCheckedLockingSingleton").newInstance();
            }
        }

        return INSTANCE;
    }

    // 应对不同的类加载器
    private static Class getClass(String classname) throws ClassNotFoundException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

        if (classLoader == null)
            classLoader = DoubleCheckedLockingSingleton.class.getClassLoader();

        return (classLoader.loadClass(classname));
    }
    
    // 应对序列化与反序列化
    private Object readResolve() 
    {
        return INSTANCE;
    }
}

  枚举方式,枚举只有一个private的构造方法,可以用来做单例模式

package creational.pattern.singleton;

enum EnumSingleton {
    INSTANCE;
}

  静态内部类方式

package creational.pattern.singleton;

/*
 * 可以实现懒加载
 */
public class StaticInnerSingleton {
    private static class SingletonHolder{
        private static StaticInnerSingleton INSTANCE = new StaticInnerSingleton();
    }
    
    private StaticInnerSingleton(){}
    
    public static StaticInnerSingleton getInstance()
    {
        return SingletonHolder.INSTANCE;
    }
}

 


亲爱的读者:有时间可以点赞评论一下

点赞(0) 打赏

全部评论

还没有评论!
广告位-帮帮忙点下广告