美文网首页
单例模式

单例模式

作者: Lamour_a9c8 | 来源:发表于2020-10-28 22:11 被阅读0次

    1.饿汉式

    /**  线程安全,调用效率高。 但是,不能延时加载**/    

    public class SingletonTest {

    private static SingletonTest s =new SingletonTest();

    private static SingletonTest getInstance() {

    return s;

    }

    }

    2.懒汉式(延时加载,懒加载,真正用的时候才加载!,但是每次调用的时候都要同步,并发效率降低了)

    public class SingletonTest {

    private static SingletonTest s;

    public static synchronized SingletonTest getInstance() {

    if(s==null) {

    s = new SingletonTest();

    }

    return s;

    }

    }

    3.双重检测锁(不是每次获取对象时都进行同步,只有第一次才同步创建以后就没必要了)

    private static SingletonTest instance =null;

    public static synchronized SingletonTest getInstance() {

    if(instance==null) {

    SingletonTest si;

    synchronized (SingletonTest.class) {

    si = instance;

    if(si == null) {

    synchronized (SingletonTest.class) {

    si = new SingletonTest();

    }

    }

    instance =si;

    }

    }

    return instance;

    }

    4.静态内部类(高效调用和延迟加载的优势)

    private static class SingletonClassInstance{

    private static final SingletonTest instance =new SingletonTest();

    }

    public static SingletonTest getInstance() {

    return SingletonClassInstance.instance;

    }

    5 枚举类

    public enum SingletonClassInstance (){

    INSTANCE;

    public void operation () {

    }

    }

    相关文章

      网友评论

          本文标题:单例模式

          本文链接:https://www.haomeiwen.com/subject/gcthvktx.html