Java学习笔记

JAVA学习笔记之单例模式

2016-11-22  本文已影响8人  红姑娘

*请问我们要掌握哪种方式?
开发:饿汉式
面试:懒汉式

*为什么?
因为饿汉式不会出现线程安全问题。
懒汉式:
线程安全问题。你要能够给比人分析出安全问题的原因,并最终提供解决方案。
延迟加载思想。(懒加载思想。)

    Runtime本身就是一个饿汉式的体现。
    public class Runtime {
        private Runtime() {}
        
        private static Runtime currentRuntime = new Runtime();
        
        public static Runtime getRuntime() {
            return currentRuntime;
        }
    }

饿汉式

//测试类StudentDemo
public class StudentDemo {
public static void main(String[] args) {
    // Student.s = null;

    Student s1 = Student.getStudent();
    Student s2 = Student.getStudent();
    System.out.println(s1 == s2);

    s1.show();
    s2.show();
}
}

 //单利类Student
public class Student {
// 保证外界不能创建对象
private Student() {
}

// 由于静态只能访问静态,所以加static修饰
// 为了不让外界直接访问,加private
private static Student s = new Student();

// 为了保证外界可以访问该对象,必须加static
public static Student getStudent() {
    return s;
}

public void show() {
    System.out.println("show");
}
}

懒汉式

 //测试类TeacherDemo
public class TeacherDemo {
public static void main(String[] args) {
    Teacher t1 = Teacher.getTeacher();
    Teacher t2 = Teacher.getTeacher();

    System.out.println(t1 == t2);
}
}

// 单利类
public class Teacher {
private Teacher() {
}

private static Teacher t = null;

public synchronized static Teacher getTeacher() {
    // t1,t2,t3,t4
    if (t == null) {
        // t1,t2,t3,t4
        t = new Teacher();
    }
    return t;
}

public void show() {
    System.out.println("show");
}
}
上一篇 下一篇

猜你喜欢

热点阅读