- 饿汉式
- public class Student {
- //为了不让外界创造该类的对象,选择构造私有化
- private Student() {
- super();
- // TODO Auto-generated constructor stub
- }
- //自己创建自己的对象
- private static Student student = new Student();
-
- //用一个方法传出该对象
- public static Student getStudent(){
-
- return student;
- }
- }
- 懒汉式(面试一般写这种)
- public class Student {
- //为了不让外界创造该类的对象,选择构造私有化
- private Student() {
- super();
- // TODO Auto-generated constructor stub
- }
- private static Student student1 = null;
- public synchronized static Student geStudent1(){
- if (student1== null) {
- student1 = new Student();
- }
-
- return student1;
- }
- }
复制代码
|
|