设计模式(二) 单例模式

定义

单例模式是一种对象创建型模式。GoF对单例模式的定义是:保证一个类、只有一个实例存在,同时提供能对该实例加以访
问的全局访问方法。

使用单例模式的原因

  • 在多个线程之间,比如servlet环境,共享同一个资源或者操作同一个对象。

  • 在整个程序空间使用全局变量,共享资源。

  • 大规模系统中,为了性能的考虑,需要节省对象的创建时间等等。

单例模式实现

  1. 饿汉式:在单线程和多线程中均无问题。

    public class Person {
    public static final Person person = new Person();
    private String name;

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    //构造函数私有化
    private Person() {
    }

    //提供一个全局的静态方法
    public static Person getPerson() {
    return person;
    }
    }

  2. 懒汉式:多线程中不能保证唯一的对象。若在多线程中使用懒汉式,可用2.1 、2.2 方式。

    public class Person2 {
    private String name;
    private static Person2 person;

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    //构造函数私有化
    private Person2() {
    }

    //提供一个全局的静态方法
    public static Person2 getPerson() {
    if(person == null) {
    person = new Person2();
    }
    return person;
    }
    }

    2.1 添加synchronized的懒汉式

    public class Person3 {
    private String name;
    private static Person3 person;

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    //构造函数私有化
    private Person3() {
    }

    //提供一个全局的静态方法,使用同步方法
    public static synchronized Person3 getPerson() {
    if(person == null) {
    person = new Person3();
    }
    return person;
    }
    }

    2.2 双重检查

    public class Person4 {
    private String name;
    private static Person4 person;

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    //构造函数私有化
    private Person4() {
    }

    //提供一个全局的静态方法
    public static Person4 getPerson() {
    if(person == null) {
    synchronized (Person4.class) {
    if(person == null) {
    person = new Person4();
    }
    }

    }
    return person;
    }
    }

posted @ 2017-09-20 15:11  esileme  阅读(166)  评论(0)    收藏  举报