版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cmm0401/article/details/82718790
Java设计模式-单例模式概述与使用
1、单例模式的概述与使用
- 单例模式,就是要确保类在内存中只有一个对象,该对象必须自动创建,并且对外提供。
- 优点:在系统内存中只存在一个对象,因此可以节约系统资源,对于一些需要频繁创建和销毁对象的方法,单例模式无疑可以提高系统的性能。
- 缺点:没有抽象层,因此扩展很难。职责过重,在一定程序上违背了单一职责。
- 单例模式的分类:
单例模式之饿汉式:类一加载的时候就创建对象。
单例模式之懒汉式:类一加载的时候并不急着去创建对象,而是在需要用的时候才去创建对象。
2、单例模式之饿汉式:开发时使用
(0)单例模式的实现步骤:3部曲
- 1)把类的构造方法私有化
- 2)在类中的成员位置自己创建一个供别人使用的唯一的类对象
- 由于静态方法只能访问静态成员变量,因此这个类对象需要加静态static修饰
- 又因为不能够让外界直接访问修改这个类对象的值,因此需要加私有修饰符private修饰
- 3)在类中提供一个对外公共的访问方式,为了让外界能够直接使用该公共访问方式,该方式需要加静态static修饰
(1)实现单例模式的学生类
package cn.itcast_03;
public class Student {
private Student() { }
private static Student s = new Student();
public static Student getStudent() {
return s;
}
}
(2)测试该单例模式
package cn.itcast_03;
/*
* 单例模式:保证类在内存中只有一个对象。
* 如何保证类在内存中只有一个对象呢?
* A:把构造方法私有
* B:在成员位置自己创建一个对象
* C:通过一个公共的方法提供访问
*/
public class StudentDemo {
public static void main(String[] args) {
// Student s1 = new Student();
// Student s2 = new Student();
// System.out.println(s1 == s2); // false
Student s1 = Student.getStudent();
Student s2 = Student.getStudent();
System.out.println(s1 == s2);
System.out.println(s1); // null,cn.itcast_03.Student@175078b
System.out.println(s2);// null,cn.itcast_03.Student@175078b
}
}
3、单例模式之懒汉式:面试时使用
(1)实现单例模式的老师类
package cn.itcast_03;
public class Teacher {
private Teacher() { }
private static Teacher t = null;
public synchronized static Teacher getTeacher() {
// 假设有三个线程 t1,t2,t3
if (t == null) {
//t1,t2,t3
t = new Teacher();
}
return t;
}
}
(2)测试该单例模式
package cn.itcast_03;
public class TeacherDemo {
public static void main(String[] args) {
Teacher t1 = Teacher.getTeacher();
Teacher t2 = Teacher.getTeacher();
System.out.println(t1 == t2);
System.out.println(t1); // cn.itcast_03.Teacher@175078b
System.out.println(t2);// cn.itcast_03.Teacher@175078b
}
}
4、单例模式的面试题
* 单例模式:
* 饿汉式:类一加载就创建对象
* 懒汉式:用的时候,才去创建对象
* 面试题:单例模式的思想是什么?请写一个代码体现?
* 开发:饿汉式(是不会出问题的单例模式)
* 面试:懒汉式(可能会出问题的单例模式)
* A:懒加载(延迟加载) :不会出问题
* B:线程安全问题:可能会出问题—— 怎么解决呢?加 同步操作符:synchronize
* a:是否多线程环境 是
* b:是否有共享数据 是
* c:是否有多条语句操作共享数据 是