码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式随笔(三):单例模式

时间:2020-07-06 10:28:05      阅读:59      评论:0      收藏:0      [点我收藏+]

标签:静态   nbsp   tin   随笔   eve   oid   singleton   static   color   

单例模式一般分为:懒汉、饿汉、双重校验锁、枚举、静态内部类五种。

 

懒汉:

第一次调用时,创建对象

public class Single {

    private static Single instance;

    private Single(){};

    public static Single getInstance() {
        if (instance == null) {
            instance = new Single();
        }
        return instance;
    }
}

饿汉:

public class Single {

    private static Single instance = new Single();

    private Single(){};

    public static Single getInstance() {
        return instance ;
    }
}

双重校验锁:

public class Single {

    private volatile static Single singleton;  //1:volatile修饰

    private Single(){}

    public static Single getSingleton() {
        if (singleton == null) {
            synchronized (Single.class) {
                if (singleton == null) {
                    singleton = new Single();
                }
            }
        }
        return singleton;
    }

}

静态内部类:

public class Single {

    private Single() {}
    public static Single getInstance() {
        return Inner.instance;
    }

    public static class Inner {
        private static final Single instance = new Single();
    }
}

枚举:

public enum Singleton {  
    INSTANCE;  
    public void whateverMethod() {  
    }  
}  

 

设计模式随笔(三):单例模式

标签:静态   nbsp   tin   随笔   eve   oid   singleton   static   color   

原文地址:https://www.cnblogs.com/chylcblog/p/13253215.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!