亲宝软件园·资讯

展开

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

取经蜗牛 人气:0
想了解Java设计模式之单例模式简介的相关内容吗,取经蜗牛在本文为您仔细讲解Java单例模式简介的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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;
    }
}

八、单例模式的优点

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

加载全部内容

相关教程
猜你喜欢
用户评论