A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

单例模式:保证类的内存只有一个对象,通过私有构造方法,自己创建对象,提供公共访问方法实现。
分两种:
饿汉式:类一加载就创建对象
懒汉式:用的时候,创建对象
面试的时候考懒汉式:因为可能会出现线程安全问题,所以记得用同步“synchronize”
开发的时候用饿汉式:因为它是不会出现问题的单例模式
public class Student {
        private Student() {
        };
       
        private static Student s = null;
       
        public synchronized static  Student getStudent() {
                if (s==null) {
                        s =new Student();
                }
                return s;
        }

}
public class StudentDemo {
        public static void main(String[] args) {
                Student s1 = Student.getStudent();
                Student s2 = Student.getStudent();
                System.out.println(s1==s2);
        }


1 个回复

倒序浏览
Runtime类就是采用单例模式的
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马