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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 648947721 中级黑马   /  2014-9-9 23:03  /  990 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

class Student
{
        //2.步骤2
        private static Student stuObj = null;
        //1.步骤1
        private Student(){
        }
        //3.步骤3
        public static Student getStudentInstance(){
                if(stuObj == null){
                        System.out.println("构造了一个Student对象");
                        stuObj = new Student();
                }
                System.out.println("返回一个Student引用");
                return stuObj;
        }
}
class Demo
{
        public static void main(String[] args)
        {
                Student stu = Student.getStudentInstance();//第一次获取,产生一个对象

                Student stu2 = Student.getStudentInstance();//之后再获取,将直接返回引用,不再产生对象
                Student stu3 = Student.getStudentInstance();
        }
}

评分

参与人数 1黑马币 +1 收起 理由
格子、 + 1

查看全部评分

5 个回复

倒序浏览

点这个用代码专用格式,会清楚一点。
回复 使用道具 举报
你单例的视频应该还没看完吧。你这写的应该是懒汉式的单例,但是你这个单例没有加同步锁。
回复 使用道具 举报
bullfrog 发表于 2014-9-9 23:22
点这个用代码专用格式,会清楚一点。

是啊是啊,谢谢
回复 使用道具 举报
陈君 发表于 2014-9-9 23:27
你单例的视频应该还没看完吧。你这写的应该是懒汉式的单例,但是你这个单例没有加同步锁。 ...

恩恩,是啊是啊,今天看了
回复 使用道具 举报
很经典啊
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马