单例

单例设计模式,就是保证对象的实例只有一个,防止每个用这个对象的人都创建一个实例。

私有化构造方法

提供对象返回方法,用static修饰

对象创建语句要是在外面,需要用 static final限定词

1、饿汉:类加载时就先把对象实例准备好。

public class SingleTon {

    private SingleTon(){}

    private static final Peopel peopel=new Peopel();

    public static Peopel getInstance(){
        return peopel;
    }

}

2、懒汉:什么时候要对象,什么时候再去创建。但是要记得加判断,即,实例为空的时候才去创建,不为空就返回,不加判断就是多例了。

public class SingleTon {

    private static People people;

private SingleTon(){} public static People getInstance(){ if(peopel==null){ people=new People(); } return people; } }

3、多线程下的单例:线程安全

public class SingleTon {

    private volatile static People people;
    private SingleTon(){}

    public static People getInstance(){
        if(peopel==null) {
            //孩子没产生,大家进去排队,抢着造人
            synchronized (People.class) {
                if (peopel == null) {
                    people = new People();
                }
            }
        }
        //孩子产生了那就不用都排队了,就去要孩子就好了
        return people;
    }

}
public class Singleton {

    private volatile static Singleton uniqueInstance;

    private Singleton() {
    }

    public static Singleton getUniqueInstance() {
       //先判断对象是否已经实例过,没有实例化过才进入加锁代码
        if (uniqueInstance == null) {
            //类对象加锁
            synchronized (Singleton.class) {
                if (uniqueInstance == null) {
                    uniqueInstance = new Singleton();
                }
            }
        }
        return uniqueInstance;
    }
}
原文地址:https://www.cnblogs.com/guoyu1/p/12000584.html