栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java设计模式之单例模式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java设计模式之单例模式

所谓类的单例设计模式,就是采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法(静态方法)。

(1)饿汉式(静态变量)
class Singleton{
    // 1、将构造器私有化,外部就不能new了
    private Singleton(){
    }
    // 2、本类内部创建对象实例
    private final static Singleton instance = new Singleton();

    // 3、提供一个公有的静态方法,返回实例对象
    public static Singleton getInstance(){
        return instance;
    }
}
(2)饿汉式(静态代码块)
class Singleton2{
    // 1、将构造器私有化,外部就不能new了
    private Singleton2(){
    }
    // 2、本类内部创建对象实例
    private  static Singleton2 instance ;

    // 静态代码块,完成对象的实例
    static {
        instance = new Singleton2();
    }

    // 3、提供一个公有的静态方法,返回实例对象
    public static Singleton2 getInstance(){
        return instance;
    }
}
(3)懒汉式(线程不安全,不推荐)
class Singleton3{
    // 1、将构造器私有化,外部就不能new了
    private Singleton3(){
    }
    // 2、本类内部创建对象实例
    private  static Singleton3 instance ;

    // 3、提供一个静态的共有方法,当使用该方法的时候,才创建对象
    // 懒汉式
    public static Singleton3 getInstance(){
        if(instance == null){
            instance = new Singleton3();
        }
        return instance;
    }
}
(4)懒汉式(线程安全,不推荐)
class Singleton4{
    // 1、将构造器私有化,外部就不能new了
    private Singleton4(){
    }
    // 2、本类内部创建对象实例
    private  static Singleton4 instance ;

    // 3、提供一个静态的共有方法,加入了同步处理的代码,当使用该方法的时候,才创建对象
    // 懒汉式
    public static synchronized Singleton4 getInstance(){
        if(instance == null){
            instance = new Singleton4();
        }
        return instance;
    }
}

(5)Double-Check(推荐)
class Singleton5{
    // 1、将构造器私有化,外部就不能new了
    private Singleton5(){
    }
    // 2、本类内部创建对象实例
    private  static volatile Singleton5 instance ;

    // 3、提供一个静态的共有方法,加入了双重检查代码,解决线程安全问题,同时解决懒加载问题
    // 同时保证了效率,推荐使用
    public static  Singleton5 getInstance(){
        if(instance == null){
            synchronized (Singleton5.class){
                if(instance == null){
                    instance = new Singleton5();
                }
            }
        }
        return instance;
    }
}
(6)静态内部类(推荐)
class Singleton6{
    // 1、将构造器私有化,外部就不能new了
    private Singleton6(){
    }
    // 静态内部类
    private static class Singleton6Instance{
        private static final Singleton6 instance = new Singleton6();
    }

    public static  Singleton6 getInstance(){
        return Singleton6Instance.instance;
    }
}
(7)枚举实现单例(推荐)
public class _08_Singleton {
    public static void main(String[] args) {
        Singleton08 instance = Singleton08.INSTANCE;
    }


}


enum Singleton08{
    INSTANCE; //属性
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/351517.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号