(二)单列模式

1.饿汉

package Singleton;

public class Singleton1 {

    private static Singleton1 mSingletion = new Singleton1();

    private Singleton1() {
    }

    public static Singleton1 getmSingletion() {
        return mSingletion;
    }

    public static void main(String[] args) {
        Singleton1.getmSingletion();
    }
}

2.懒汉

package Singleton;

public class Singleton2 {
    private static Singleton2 mSingleton2;

    private Singleton2() {
    }

    public static Singleton2 getmSingleton2() {
        if (mSingleton2 == null) {
            mSingleton2 = new Singleton2();
        }
        return mSingleton2;
    }

    public static void main(String[] args) {
        Singleton2.getmSingleton2();
    }
}

3.双重锁校验

package Singleton;

public class SingletonDouble {
    private static volatile SingletonDouble mSingletonDouble;

    private SingletonDouble() {
    }

    public static SingletonDouble getmSingletonDouble() {
        if (mSingletonDouble == null) {
            synchronized (SingletonDouble.class) {
                if (mSingletonDouble == null) {
                    mSingletonDouble = new SingletonDouble();
                }
            }
        }
        return mSingletonDouble;
    }
}

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