06. Singleton模式代码

    6. Singleton 本质:控制实例数目
      6.1 EAGER SINGLETON
        public class AppConfigEager {
            private AppConfigEager() {
                readConfig();
            }
            private static final AppConfigEager INSTANCE = new AppConfigEager();
            public static AppConfigEager getInstance() {
                return INSTANCE;
            }
            private String parameterA;
            private String parameterB;
            public String getParameterA() {
                return parameterA;
            }
            public String getParameterB() {
                return parameterB;
            }
            private void readConfig() {
                Properties p = new Properties();
                InputStream in = null;
                try {
                    in = AppConfigEager.class.getResourceAsStream("AppConfig.properties");
                    p.load(in);
                    this.parameterA = p.getProperty("paramA");
                    this.parameterB = p.getProperty("paramB");
                    
                } catch (Exception e) {
                    System.out.println("Load app config file error.");
                    e.printStackTrace();
                } finally {
                    try {
                        in.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
      6.2 LAZY INITIALIZATION HOLDER SINGLETON
        public class Singleton {
            private Singleton(){
            }
            private static class SingletonLazyInitHolder {
                private static Singleton instance = new Singleton();
            }
            public static Singleton getInstance() {
                return SingletonLazyInitHolder.instance;
            }
        }
      6.3 ENUM SINGLETON
        public enum SingletonEnum {
            INSTANCE;
            private int count = 0;
            public void countPlusOne() {
                count++;
                System.out.println("count: " + count);
            }
        }
        public class SingletonEnumClient {
            public static void main(String[] args) {
                SingletonEnum.INSTANCE.countPlusOne();
                SingletonEnum.INSTANCE.countPlusOne();
                SingletonEnum.INSTANCE.countPlusOne();
            }
        }


 

阅读更多
个人分类: 设计模式
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭