美文网首页
Java,Kotlin,Dart 实现单例模式

Java,Kotlin,Dart 实现单例模式

作者: 鹅鹅鹅曲项向天歌呀 | 来源:发表于2022-10-30 10:01 被阅读0次

记录三种语言实现单例的写法~~
方式有很多种,用自己喜欢的~

Java

public class Student {
    private volatile static Student student;

    private Student() {
    }

    public static Student getStudentIns() {
        if (student == null) {
            synchronized (Student.class) {
                if (student == null) {
                    student = new Student();
                }
            }
        }
        return student;
    }
}

Kotlin

class Teacher private constructor() {
    companion object {
        val teacherIns: Teacher by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            Teacher()
        }
    }
}

Dart

class Apple {
  Apple._getApple();
  static Apple _apple = Apple._getApple();
  factory Apple.getAppIns() => _apple;
}

相关文章

网友评论

      本文标题:Java,Kotlin,Dart 实现单例模式

      本文链接:https://www.haomeiwen.com/subject/qqwktdtx.html