Singleton的7种实现

来源:互联网 发布:如何判断域名被劫持 编辑:程序博客网 时间:2024/06/07 22:58

随便写写,万一将来碰到呢,也有个印象不是

两个概念:

懒汉式:lazy,很多地方都有这个词,延时加载-即用到的时候才去创建单例的实例。非线程安全。

恶汉式:加载类的时候就创建好唯一实例。恶汉式是线程安全的,因为类只会被加载一次。


public class TestSingleton {    public static void main(String[] args){        System.out.println(Singleton1.getInstance().toString());    }    static class Singleton1{        private static Singleton1 instance;        private Singleton1(){        }        public static Singleton1 getInstance(){            if (instance == null){                instance = new Singleton1();            }            return instance;        }    }    static class Singleton2{        private static Singleton2 instance = new Singleton2();        private Singleton2(){        }        public static Singleton2 getInstance(){            return instance;        }    }    static class Singleton3{        private static Singleton3 instance;        private Singleton3(){        }        static {            instance = new Singleton3();        }        public static Singleton3 getInstance(){            return instance;        }    }    static class Singleton4{        private static Singleton4 instance;        private Singleton4(){        }        public static synchronized Singleton4 getInstance(){            if (instance == null){                instance = new Singleton4();            }            return instance;        }    }    static class Singleton5{        private static final class InnerClass{            public static final Singleton5 INSTANCE = new Singleton5();        }        public static Singleton5 getInstance(){            return InnerClass.INSTANCE;        }    }    static class Singleton6{        private static volatile Singleton6 instance;        private Singleton6(){        }        public static Singleton6 getInstance(){            if (instance == null){                synchronized (Singleton6.class){                    if (instance == null){                        instance = new Singleton6();                    }                }            }            return instance;        }    }    public enum Singleton7{        INSTANCE;    }}


原创粉丝点击