java单例的几种实现方法

java单例的几种实现方法:

方式1:

public class Something {
    private Something() {}

    private static class LazyHolder {
        private static final Something INSTANCE = new Something();
    }

    public static Something getInstance() {
        return LazyHolder.INSTANCE;
    }
}

方式2:

public class Singleton {
    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return INSTANCE;
    }
}

方式3:

public class Singleton {
    private static final Singleton instance;

    static {
        try {
            instance = new Singleton();
        } catch (Exception e) {
            throw new RuntimeException("Darn, an error occurred!", e);
        }
    }

    public static Singleton getInstance() {
        return instance;
    }

    private Singleton() {
        // ...

    }
}

方式4:

public enum Singleton {
    INSTANCE;
    public void execute (String arg) {
        // Perform operation here
    }
}

方式5:

public class SingletonDemo {
    private static volatile SingletonDemo instance;
    private SingletonDemo() { }

    public static SingletonDemo getInstance() {
        if (instance == null ) {
            synchronized (SingletonDemo.class) {
                if (instance == null) {
                    instance = new SingletonDemo();
                }
            }
        }

        return instance;
    }
}

方式6:

 public class ComplexObjectInitializer extends LazyInitializer<complexobject> {
     @Override
     protected ComplexObject initialize() {
         return new ComplexObject();
     }
 }

 // Create an instance of the lazy initializer
 ComplexObjectInitializer initializer = new ComplexObjectInitializer();
 ...

 // When the object is actually needed:
 ComplexObject cobj = initializer.get();
</complexobject>

方式7:

使用guava:

 private static final Supplier<string> tokenSup = Suppliers.memoize(new Supplier<string>() {
        @Override
        public String get() {
            //do some init
            String result = xxx;
            return result;
        }
    });
</string></string>

Original: https://www.cnblogs.com/rollenholt/p/4774063.html
Author: Rollen Holt
Title: java单例的几种实现方法

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/537990/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球