郑州手机网站推广外包,做一个代驾app需要多少钱,wordpress is_single,如何注销网站单利设计模式 A#xff1a;保证对象在内存中只有一个。 B#xff1a;如何保证#xff1f; **不能让其他类来创建对象。 **本类中要创建一个本类对象。 **对外提供公共的访问。 C#xff1a;步骤 我们的类是Student **private Student(){} **Student s new Student(); **p…单利设计模式 A保证对象在内存中只有一个。 B如何保证 **不能让其他类来创建对象。 **本类中要创建一个本类对象。 **对外提供公共的访问。 C步骤 我们的类是Student **private Student(){} **Student s new Student(); **public Student getInstance(){return s;} 单利的两种方式 第一种方式饿汉式 class Teacher{ //本类创建一个对象 private static Teacher t new Teacher(); //为了保证其他类不能够创建对象 private Teacher(){} //为了外界能够通过类名直接调用 public static Teacher getInstance(){ return t; } } Teacher t1 Teacher.getInstance(); Teacher t2 Teacher.getInstance(); 第二种方式懒汉式 class Teacher{ //本类创建一个对象 private static Teacher t null; //为了保证其他类不能够创建对象 private Teacher(){} //为了外界能够通过类名直接调用 public static Teacher getInstance(){ if(tnull){ Synchronized(Teacher.class){ if(tnull){ t new Teacher(); } } } return t; } } Teacher t1 Teacher.getInstance(); Teacher t2 Teacher.getInstance(); 注意开发一般用饿汉式。第二种在多线程的时候会有安全隐患。 面试一般考懒汉式(延迟加载) 工具类构造私有方法静态。直接使用类名调用工具类一般没有访问数据创建对象没啥意义。 转载于:https://www.cnblogs.com/wangxuekui/p/9404750.html