单例模式

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 单例模式
 * 要点:私有化构造函数
 *         对象为类的属性
 */
public class Singleton {
    public static void main(String[] args) {
        //可以用对象方法
        Singleton_01 singleton_01 = Singleton_01.getSingleton_01();
        //直接用类的方法
        Singleton_01.doSomething();
    }
}
//饿汉,线程安全
class Singleton_01{
    private Singleton_01(){}//1.私有化,不让外部创建
    private static Singleton_01 singleton_01 = new Singleton_01();//2.类加载的时候就创建
    //必须为静态哇,不然外面调不了
    public static Singleton_01 getSingleton_01(){
        return singleton_01;
    }
    //类中其他方法,尽量是static,类方法,与对象没啥关系
    public static void doSomething(){
    }
}
//懒,线程有隐患,用个加锁解决吧
class Singleton_02{
    static Lock lock = new ReentrantLock();
    private Singleton_02(){}
    private static Singleton_02 singleton_02 = null;
    public static Singleton_02 getSingleton_02(){
        lock.lock();
        //线程同时卡在这儿的话,会进入再次创建
        if (singleton_02 == null) {
            singleton_02 = new Singleton_02();
        }
        lock.unlock();
        return singleton_02;
    }
}
//双重加锁,当已经创建过实例对象后就无需加锁,提高效率
class Singleton_03 {
    private Singleton_03(){}
    private static Singleton_03 singleton;

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

 

 

 

posted @ 2018-04-14 17:11  涂鸟少年  阅读(93)  评论(0编辑  收藏  举报