GOF23种设计模式之单例模式

2020-02-11  本文已影响0人  手打小黑板

饿汉式

package com.liming.singleton;

import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.CountDownLatch;

public class Singleton {
     private static Singleton instance = new Singleton();
    private Singleton(){}

    public static Singleton getInstance() {
        return instance;
    }

    public static void main(String[] args) throws InterruptedException {

       final CountDownLatch cdl = new CountDownLatch(10);

        long startTime = System.currentTimeMillis();

        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                for (int j = 0; j < 1000000; j++) {
                    Singleton sl = Singleton.getInstance();
                }
                cdl.countDown();
            }).start();

        }

        cdl.await();

        System.out.println(System.currentTimeMillis() - startTime);


    }

    public static void main2(String[] args) {//反序列化破解单例模式
        SingletonLazy singleton = SingletonLazy.getInstance();
        System.out.println(singleton);
        System.out.println(SingletonLazy.getInstance());

        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("res/kkk.xbj"));
            oos.writeObject(singleton);
            oos.flush();
            oos.close();

            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("res/kkk.xbj"));
            System.out.println(ois.readObject());
            ois.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    //
    public static void main1(String[] args) {

        SingletonLazy singleton = SingletonLazy.getInstance();
        System.out.println(singleton);
        System.out.println(SingletonLazy.getInstance());

        try {
            Class<SingletonLazy> xlass = (Class<SingletonLazy>)Class.forName(SingletonLazy.class.getName());
            Constructor<SingletonLazy> cstr = xlass.getDeclaredConstructor();
            cstr.setAccessible(true);
            System.out.println(cstr.newInstance());

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


    }
}

//饿汉式单例模式

懒汉式

package com.liming.singleton;

import java.io.Serializable;
import java.util.concurrent.RejectedExecutionException;

public class SingletonLazy implements Serializable {
    private static volatile SingletonLazy instance;
    private SingletonLazy(){
        if (instance != null) {
            throw new RuntimeException("单例模式禁止反射调用");
        }
    }

    public static synchronized SingletonLazy getInstance(){

        if (instance == null) {
            instance = new SingletonLazy();
        }

        return instance;

    }

    private Object readResolve(){   //防止反序列化破解单例模式 序列化时返回已创建的单例模式对象
        return instance;
    }

}

//懒汉式单例模式

省时懒汉式

package com.liming.singleton;

public class SingletonLazyFast {
    private static volatile SingletonLazyFast instance;
    private SingletonLazyFast(){}

    public static SingletonLazyFast getInstance(){

        if (instance != null) { //volatile保证访问此成员时总是最新的数据,避免指令重排造成数据不同步
            return instance;
        }

        synchronized (SingletonLazyFast.class) {
            if (instance == null) {
                instance = new SingletonLazyFast();
            }
        }

        return instance;
    }
}

//volatile单例模式

静态内部类式

package com.liming.singleton;

public class SingletonStaticInnerClass {
    private static class SingletonClassInstance {
        public static final SingletonStaticInnerClass INSTANCE = new SingletonStaticInnerClass();
    }

    public static SingletonStaticInnerClass getInstance(){
       return SingletonClassInstance.INSTANCE;
    }

    private SingletonStaticInnerClass(){}


}

//内部类单例模式

上一篇下一篇

猜你喜欢

热点阅读