美文网首页
单例模式的实现

单例模式的实现

作者: 树心图物 | 来源:发表于2019-04-24 17:31 被阅读0次

    饿汉式:

    public class A {
    private static A a = new A();
    private A() {
    }
    public static A getInstance() {
    return a;
    }
    }
    

    懒汉式:(线程不安全)

    public class A {
    private static A a = null;
    private A() {
    }
    public static A getInstance() {
    If a == null {
    A = new A();
    }
    return a;
    }
    }
    

    懒汉式:(线程安全方式但不推荐)

    public class A {
    private static A a = null;
    private A() {
    }
    public static synchronized A getInstance() {
    If a == null {
    A = new A();
    }
    return a;
    }
    }
    

    懒汉式:(线程安全方式但有几率出错,因为对象的内存申请和初始化不同步的原因)

    public class A {
    private static A a = null;
    private A() {
    }
    public static synchronized A getInstance() {
    synchronized (A.class){
    If a == null {
    A = new A();
    }
    }
    return a;
    }
    }
    

    静态内部类方式:(推荐)

    public class A {    
        private static class AHolder {    
            private static A a = new A();    
        }    
        private A (){}    
        public static A getInstance() { 
            return AHolder.a;   
        }    
    }  
    

    相关文章

      网友评论

          本文标题:单例模式的实现

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