java设计模式之单例设计模式

单例设计模式

  1. 保证一个类在使用过程中,只有一个实例。优势就是他的作用,这个类永远只有一个实例。
  2. 优势:这个类永远只有一个实例,占用内存少,有利于Java垃圾回收。

单例设计模式关键点

  1. 私有的构造方法。
  2. 提供一个外界能够访问的方法。 

单例模式代码演示

  1. 懒汉模式(延迟加载)
    package test;
    //懒汉模式
    public class Teacher {
        private static Teacher tea=null;
        private Teacher(){}//提供私有的构造方法
        //提供外界能够访问的静态方法
        public static Teacher getTeacher(){
            if(tea==null){
                tea=new Teacher();
            }
            return tea;
        }
    }
  2. 饿汉模式(饿汉式是线程安全的,在类创建的同时就已经创建好一个静态的对象供系统使用,以后不在改变。)
    package test;
    //懒汉模式
    public class Teacher {
        private static Teacher tea=null;
        private Teacher(){}//提供私有的构造方法
        //提供外界能够访问的静态方法
        public static Teacher getTeacher(){
            if(tea==null){
                tea=new Teacher();
            }
            return tea;
        }
    }
  3. 测试类:
    package test;
    
    public class Test {
        public static void main(String[] args) {
            Student student = Student.getStudent();
            System.out.println(student);
            Teacher teacher = Teacher.getTeacher();
            System.out.println(teacher);
        }
    }

  

猜你喜欢

转载自www.cnblogs.com/tysl/p/10035459.html