java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java单例模式简介

Java设计模式之单例模式简介

作者:取经蜗牛

这篇文章主要介绍了Java设计模式之单例模式简介,文中有非常详细的代码示例,对正在学习Java的小伙伴们有非常好的帮助,需要的朋友可以参考下

一、饿汉式(静态常量)

public class Face {
        private static final Face instance = new Face();
 
        static Face getInstance() {
            return instance;
        }
 
        private Face() {
        }
    }

二、饿汉式(静态代码块)

public class Face {
        private static Face instance;
 
        static {
            instance = new Face();
        }
 
        private Face() {
        }
 
        public static Face getInstance() {
            return instance;
        }
    }

三、懒汉式(线程不安全)

public class Face {
    private static Face instance;
 
    private Face() {
    }
 
    public static Face getInstance() {
        if (null == instance) {
            instance = new Face();
        }
        return instance;
    }
}

四、懒汉式(线程安全,同步方法)

public class Face {
    private static Face instance;
 
    private Face() {
    }
 
    public static synchronized Face getInstance() {
        if (null == instance) {
            instance = new Face();
        }
        return instance;
    }
}

五、懒汉式(线程不安全,同步代码块)

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

六、双重检查( DCL )

public class Face {
    private static volatile Face instance;
 
    private Face() {
    }
 
    public static Face getInstance() {
        if (null == instance) {
            synchronized (Face.class) {
                if (null == instance) {
                    instance = new Face();
                }
            }
        }
        return instance;
    }
}

七、静态内部类

public class Face {
    private static volatile Face instance;
 
    private Face() {
    }
 
    private static class FaceInstance {
        private static final Face faceInstance = new Face();
    }
 
    public static Face getInstance() {
        return FaceInstance.faceInstance;
    }
}

八、单例模式的优点

可以减少系统内存开支,减少系统性能开销,避免对资源的多重占用、同时操作

到此这篇关于Java设计模式之单例模式简介的文章就介绍到这了,更多相关Java单例模式简介内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文