单例设计模式

32次阅读

共计 1873 个字符,预计需要花费 5 分钟才能阅读完成。

  1. 单例:一个类只能有惟一一个实例对象;
  2. 如何实现单例?
    1)饿汉式:不管使用者是否须要这个对象,都间接先创立好这个对象;

    //① 枚举
    public class SingletonPattern1 {public static void main(String[] args) {
            SingleEnum singleEnum1 = SingleEnum.INSTANCE;
            SingleEnum singleEnum2 = SingleEnum.INSTANCE;
            System.out.println(singleEnum1==singleEnum2);//true
        }
    }
    enum SingleEnum{INSTANCE}
    //② 结构器私有化,用全局的动态变量来保留这个惟一的实例对象;public class SingletonPattern2 {public static void main(String[] args) {
    
            Single single1 = Single.INSTANCE;
            Single single2 = Single.INSTANCE;
        
            System.out.println(single1==single2);//true
        }
    }
    
    class Single{public static final Single INSTANCE = new Single();
    
        private Single(){}
    }
    //③ 结构器私有化,用公有的动态称量来保留这个惟一的实例对象,提供静态方法返回这个常量对象;public class SingletonPattern3 {public static void main(String[] args) {SingleClass single1 = SingleClass.getInstance();
            SingleClass single2 = SingleClass.getInstance();
            System.out.println(single1==single2);//true
        }
    }
    
    class SingleClass{private static final SingleClass INSTANCE = new SingleClass();
    
        private SingleClass(){}
        public static SingleClass getInstance(){return INSTANCE;}
    }

    2)懒汉式:提早创建对象,只有当使用者应用的时候才来创立这个对象;

    //① 一般模式
    public class SingletonPattern4 {public static void main(String[] args) {SingleClass4 single1 = SingleClass4.getINSTANCE();
            SingleClass4 single2 = SingleClass4.getINSTANCE();
            System.out.println(single1==single2);
        }
    }
    
    class SingleClass4{
        private static SingleClass4 INSTANCE;
        private SingleClass4(){}
    
        public static SingleClass4 getINSTANCE(){if (INSTANCE == null) { // 提高效率
                synchronized (SingleClass4.class) { // 保障线程平安
                    if (INSTANCE == null) { // 判断 实现单例
                        INSTANCE = new SingleClass4();}
                }
            }
            return INSTANCE;
        }
    }    
    //② 外部类模式:public class SingletonPattern5 {public static void main(String[] args) {SingleClass5 s1 = SingleClass5.getINSTANCE();
            SingleClass5 s2 = SingleClass5.getINSTANCE();
            System.out.println(s1==s2);
        }
    }
    class SingleClass5{
    
        // 私有化结构器
        private SingleClass5(){}
        // 创立外部类 创立外部类的惟一对象;static class Inner{private static final SingleClass5 INSTANCE = new SingleClass5();
        }
        // 定义方法提供类对象
        public static SingleClass5 getINSTANCE(){return Inner.INSTANCE;}
    }

申明:本文章是自学后编写,仅供参考,如有疏漏之处感激斧正;

正文完
 0