单例模式
单例模式,是一种常用的软件设计模式,Java设计模式之一。
在它的核心结构中只包含一个被称为单例的特殊类。
通过单例模式可以保证系统中,应用该模式的一个类只有一个实例。即一个类只有一个对象实例
具体实现
- 饿汉模式
public class Person {
/**属性:private、static修饰,类型为当前类类型,且立即初始化 */
private static Person person = new Person();
/**
* 构造方法必须私有
*/
private Person() {
System.out.println(" 这里是饿汉式的私有构造方法!");
}
/**
* public、通过get当前类的对象
* @return
*/
public static Person getPerson() {
return person;
}
}
//测试类
class TestPerson {
public static void main(String[] args) {
//static方法,直接通过类调用进行对象初始化
Person person1 = Person.getPerson();
Person person2 = Person.getPerson();
//属于同一个对象
System.out.println(person1 == person2);
}
- 懒汉(饱汉)模式
public class Student {
/**属性:private、static修饰,类型为当前类类型,不先初始化,只先声明 */
private static Student student;
/**
* 构造方法必须私有
*/
private Student() {
System.out.println("这里是懒汉模式的私有构造方法!");
}
/**
* public、通过get当前类的对象(首次使用需要实例化)
* @return student
*/
public static Student getStudentInstence() {
if(student == null)
student = new Student();
return student;
}
}
//测试类
class TestStudent {
public static void main(String[] args) {
//static方法,直接通过类调用进行对象初始化
Student stu1 = Student.getStudentInstence();
Student stu2 = Student.getStudentInstence();
//属于同一个对象
System.out.println(stu1 == stu2);
}
}