关闭

06. Singleton模式代码

419人阅读 评论(0) 收藏 举报

    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();
            }
        }


 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:42527次
    • 积分:684
    • 等级:
    • 排名:千里之外
    • 原创:23篇
    • 转载:0篇
    • 译文:0篇
    • 评论:22条
    最新评论