前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Singleton

Singleton

作者头像
用户3004328
发布2018-09-06 17:03:37
3070
发布2018-09-06 17:03:37
举报
文章被收录于专栏:增长技术增长技术

Swift

代码语言:javascript
复制
//: 第一种实现方式  懒汉
class Singleton: NSObject {
    class var shared: Singleton{
        dispatch_once(&Inner.token){
            Inner.instance = Singleton()
        }
        return Inner.instance!
    }

    struct Inner {
        static var instance: Singleton?
        static var token: dispatch_once_t = 0
    }
}

//: Test

let singleton1 = Singleton.shared
let singleton2 = Singleton.shared
assert(singleton1 === singleton2, "pass")


//: 第二种实现方式  饿汉
class Singleton2: NSObject{
    class var shared: Singleton2{
        return Inner.instance
    }

    struct Inner {
        static let instance = Singleton2()  //static 优化过 lazy load
    }
}

Java

代码语言:javascript
复制
/**
 * lazy not thread safe
 */
class Singleton {
    private static Singleton instance;

    private Singleton() {
    }

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

    /**
     * lazy thread safe
     * @return
     */
    public static synchronized Singleton getInstance2(){
        if (instance == null){
            instance = new Singleton();
        }
        return instance;
    }
}


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

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

class Singleton4{
    private static class SingletonHolder{
        private static final Singleton4 INSTANCE = new Singleton4();
    }
    private Singleton4(){}
    public static final Singleton4 getInstance(){
        return SingletonHolder.INSTANCE;
    }
}

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


class Singleton6{
    private volatile static Singleton5 singleton6;
    private Singleton6(){}
    public static Singleton6 getInstance(){
        if (singleton6 == null){
            synchronized (Singleton6.class){
                if (singleton6 == null){
                    singleton6 = new Singleton6();
                }
            }
        }
        return singleton6;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-10-31,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Swift
  • Java
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档