- 饿汉式:
- public class Student {
- private Student(){
-
- }
- private static Student s=new Student();
- public static Student getStudent(){
- return s;
-
- }
- public void show(){
- System.out.println("hello");
- }
- }
- 懒汉式:最重要注意的就是程式锁synchronized,其次加了一个if语句,其它的跟饿汉式一样
- public class Teacher {
- private Teacher(){
-
- }
- private static Teacher t=null;
- public synchronized static Teacher getTeacher(){
- if(t==null){
- t=new Teacher();
- }
- return t;
- }
- public void show(){
- System.out.println("world");
- }
- }
复制代码 关于饿汉式和懒汉式最重的的得注意构造方法的private修饰,还有定义成员变量private加static修饰
|
|