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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

一,单例设计模式
    作用是用来解决一个类在内存中只存在一个对象。

1,用代码体现位:
   1.1 将构造函数私有化;
   1.2 在类中创建一个私有并静态的对象;
   1.3 提供一个方法可以获取该对象。

2,用法:
   对于事物,应该怎样描述还是怎样描述。当需要将事物的对象保证在内存中唯一时,就将以上三步加上即可。

3,单例设计模式的两种形式:
   3.1 饿汉式(高效,安全,多用于开发)
   3.2 懒汉式(不常用,多用于面试)

饿汉式:
        class Single01
          {
                private Single01(){};
                private static Single01 s = new Single01();
                public static Single01 getInstance()
                {
                        return s;
                }
        }

        class Demo
        {
                public static void main(String[] args)
                {
                        Single01 s1 =Single01.getInstance();//s1,s2的引用指向同一个对象。
                        Single01 s2 =Single02.getInstance();
                }
        }

懒汉式:
        class Single02
        {
                private static Single02 s =null;
                private Single(){};
                private static Single02 Instance()
                {
                        if(s==null)
                        {
                            sychronized (Single02.class)//双重判断,提高了安全性。
                            {
                                if(s==null)
                                s = new Single02;
                                }
                        }
                        return s;               
                }
        }

        class Demo
        {
                public static void main(String[] args)
                {
                        Single01 s1 =Single01.getInstance();//只有调用getInstance方法时,对象才建立。
                        Single01 s2 =Single02.getInstance();
                }
        }

1 个回复

倒序浏览
是这样的。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马