欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

单利模式

程序员文章站 2022-07-04 08:44:00
...

1、饿汉式

package com.company;

/**
 * 饿汉式
 * Created by dra on 2017/7/7.
 */
public class Person {


    private String name;

    private static final Person PERSON = new Person();

    private  Person(){}

    public String getName() {
        return name;
    }

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

    /**
     * 获取单利
     * @return
     */
    public static Person getPerson(){
        return PERSON;
    }
}

2、懒汉式

package com.company;

/**
 * 懒汉式
 * Created by dra on 2017/7/7.
 */
public class Person2 {


    private String name;

    private static Person2 person;

    private Person2(){}

    public String getName() {
        return name;
    }

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

    /**
     * 获取单利
     * @return
     */
    public static Person2 getPerson(){
        if (person == null){
            person= new Person2();
        }

        return person;
    }
}

3、双重检查

package com.company;

/**
 * 双重检查
 * Created by dra on 2017/7/7.
 */
public class Person2 {


    private String name;

    private static Person2 person;

    private Person2(){}

    public String getName() {
        return name;
    }

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

    /**
     * 获取单利
     * @return
     */
    public static Person2 getPerson(){
        if (person== null){
            synchronized (Person2.class){
                if (person== null){
                    person= new Person2();
                }
            }
        }
        return person;
    }
}

转载于:https://www.jianshu.com/p/0dffbcb97d44