java设计模式之单例模式

date: 2016.12.23; modification:2016.12.23

目录:

1 设计要点

2 饿汉式

    
    public class SingletonTest {
        private static SingletonTest instance = new SingletonTest();

        private SingletonTest() {
            System.out.println("SingletonTest ctr");
        }

        public static SingletonTest getInstance() {
            return instance;
        }

        System.out.println("Start");
        System.out.println(SingletonTest.getInstance());
        System.out.println(SingletonTest.getInstance());
    }

3 懒汉式


    public class SingletonTest {
        private static SingletonTest instance;

        private SingletonTest() {
            System.out.println("SingletonTest ctr");
        }

        public static synchronized SingletonTest getInstance() {
            if (instance == null) {
                instance = new SingletonTest();
            }

            return instance;
        }

        public static void main (String [] args) {
            System.out.println("Start");
            System.out.println(SingletonTest.getInstance());
            System.out.println(SingletonTest.getInstance());
        }
    }

4 静态内部类

    private static class Instance {
        private static SingletonTest instance = new SingletonTest();
    }synchronized 

    private SingletonTest() {
        System.out.println("SingletonTest ctr");
    }

    public static SingletonTest getInstance() {
        return Instance.instance;
    }


    public class SingletonTest {

        public static void main (String [] args) {
            System.out.println("Start");
            System.out.println(SingletonTest.getInstance());
            System.out.println(SingletonTest.getInstance());
        }
    }

5 枚举式


    public class SingletonTest {
        public enum Singleton {
            INSTANCE; // 此为单例
        }
    }

6 测试效率的方法

    
    public static void main (String [] args) throws Exception {
        int threadNum = 10;
        final CountDownLatch countDownLatch = new CountDownLatch(threadNum);

        System.out.println("Start");
        long start = System.currentTimeMillis();
        
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int j = 0; j < 10000000; j++) {
                        SingletonTest s = SingletonTest.getInstance();
                    }

                    countDownLatch.countDown();
                }
            }).start();
        }

        countDownLatch.await();

        long end = System.currentTimeMillis();
        System.out.println("Time:" + (end - start));
    }