Java,Kotlin,Dart 实现单例模式

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

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;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容