单例设计模式

单例设计模式概述

单例设计就是要确保类在内存中只有一个对象,该实例必须自动创建,并且对外提供。

优点

在系统内存中只存在一个对象,因次可以节约系统资源,对于一些需要频繁创建和销毁的对象单例模式无疑可以提高系统的性能。

缺点

没有抽象层,因次扩展很难

职责锅中,在一定程序上违背了单一职责

* 单例模式
* 饿汉式:类一加载就创建对象
* 懒汉式:用的时候,才创建对象
*
* 开发:饿汉式(不会出问题的单例模式)
* 面试:懒汉式(可能会出问题的单例模式)
*
* A:延迟加载
*
* B:线程安全问题
* B1:是否多线程环境
* B2:是否有共享数据
* B3:是否有多条语句操作共享数据

饿汉式

public class IntegerDemo {
	public static void main(String[] args) {
		Student s1 = Student.getStudent();
		Student s2 = Student.getStudent();

		System.out.println(s1 == s2);
	}
}

class Student {
	private Student() {

	}

	private static Student student = new Student();

	public static Student getStudent() {
		return student;
	}
}

懒汉式

/*
 * 单例模式
 * 饿汉式:类一加载就创建对象
 * 懒汉式:用的时候,才创建对象
 * 
 * 开发:饿汉式(不会出问题的单例模式)
 * 面试:懒汉式(可能会出问题的单例模式)
 * 
 * A:延迟加载
 * 
 * B:线程安全问题
 * B1:是否多线程环境
 * B2:是否有共享数据
 * B3:是否有多条语句操作共享数据
 * */

public class IntegerDemo {
	public static void main(String[] args) {
		Teacher teacher1 = Teacher.getTeacher();
		Teacher teacher2 = Teacher.getTeacher();

		System.out.println(teacher1 == teacher2);
	}
}

class Teacher {
	private Teacher() {

	}

	private static Teacher teacher = null;

	public synchronized static Teacher getTeacher() {// 记得加上synchronized
		if (teacher == null) {
			teacher = new Teacher();
		}
		return teacher;
	}
}
原文地址:https://www.cnblogs.com/denggelin/p/6348698.html