单例设计模式

来源:互联网 发布:understand mac 破解 编辑:程序博客网 时间:2024/06/14 22:19

简介

单例模式,是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中一个类只有一个实例。即一个类只有一个对象实例。—《百度百科》

实现方法

  • 构造方法私有化;
  • 提供一个公共的静态方法,此方法获取一个当前类对象;
  • 类中定义一个私有的静态当前类引用。

代码实现

  • 懒汉式(常用):在真正用到的时候才会去创建对象
public class User {    /**     * 懒汉式     */    private static User user=null;    private User() {}    private static User getUserInstance(){        if(user==null){            user=new User();        }        return user;    }}

但是懒汉式存在线程安全问题,可以使用同步锁机制,只需在获取实例的方法上加上Synchronized即可。
当使用同步锁机制后,又会存在另一个问题,就是在多线程并发访问的情况下,每个线程每次获取实例都要判断下锁,效率比较低,为了提高效率,我们可以使用双重判断的方法。

public class User02 {    /**     * 懒汉式,解决使用双重判断解决,多线程并发访问效率低的问题     * 类锁:在代码中的方法上加了static和synchronized的锁,     * 或者synchronized(xxx.class)的代码段     */    private static User02 user=null;    private User02() {}    private static User02 getUserInstance(){        //如果第一个线程获取了单例的实例对象        //后面线程再获取实例的时候不需要进入同步代码块中了        if(user==null){            //同步代码块用的锁是单例的字节码文件对象,且只能用这个锁            synchronized (User02.class) {                if(user==null){                    user=new User02();                }            }        }        return user;    }}
  • 饿汉式:一开始就会建立单例对象
public class Student {    /**     * 恶汉式     */    private static Student student=null;    private Student() {}    static{        student=new Student();    }    private static Student getStudentInstance(){        return student;    }}

注意:Servlet并不是单例,只是容器只实例化它一次,表现出单例的效果而已