单例模式

单例的特点

  1. 不能重复实例化,所以构造方法是空的,private
  2. 提供一个共有的静态方法,调用取出单实例
  3. 要满足线程安全

单例有几种写法,有饿汉懒汉之分
懒汉就是lazy load,在有被调用的时候,才初始化实例。缺点是,为了线程安全,方法会加锁,性能上有浪费。
饿汉是在jvm加载的时候就已经初始化。缺点就是如果单例的类一直没被调用,造成浪费资源。

以下列举下推荐使用的几种写法。
饿汉模式:

package com.lxqn.jiapeng.design;

/**
 * 饿汉
 * Created by jiapeng on 2017/10/9.
 */
public class Singleton {

    private Singleton() {};

    private static final Singleton singleton = new Singleton();

    public static Singleton getInstance(){
        return singleton;
    }
}
package com.lxqn.jiapeng.design;

/**
 * 饿汉内部类
 * Created by jiapeng on 2017/10/9.
 */
public class Singleton2 {

    private Singleton2() {};

    public static Singleton2 getInstance(){
        return InnerClass.INSTANCE;
    }

    private static class InnerClass {
        private static final Singleton2 INSTANCE = new Singleton2();
    }
}

懒汉模式

package com.lxqn.jiapeng.design;

/**
 * 懒汉
 * Created by jiapeng on 2017/10/9.
 */
public class Singleton1 {

    private Singleton1(){};

    private static Singleton1 singleton=null;

    public static synchronized Singleton1 getInstance(){
        if(singleton == null){
            singleton = new Singleton1();
        }
        return singleton;
    }
}
package com.lxqn.jiapeng.design;

/**
 * 懒汉双重效验
 * Created by jiapeng on 2017/10/9.
 */
public class Singleton4 {

    private Singleton4() {};

    private static volatile Singleton4 INSTANCE;

    public static Singleton4 getInstance() {
        if (INSTANCE == null) {
            synchronized(Singleton4.class){
                if(INSTANCE == null) {
                    INSTANCE = new Singleton4();
                }
            }
        }
        return INSTANCE;
    }
}

你可能感兴趣的:(单例模式)