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;
}

你可能感兴趣的:(Java,Kotlin,Dart 实现单例模式)