注:因未学习到线程,所以以下部分均不考虑线程安全情况
一、单例设计模式
1.1 单例模式是什么
是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中,应用该模式的类一个类只有一个实例。即一个类只有一个对象
1.2 特点
1、单例类只能有一个实例。2、单例类必须自己创建自己的唯一实例。
3、单例类必须给所有其他对象提供这一实例。
二、使用步骤
1.1 饿汉模式实现
只要类Customer被加载就会初始化instance并且一直占用内存public class SingletonTest {
public static void main(String[] args) {
Customer cus1 = Customer.getInstance();
Customer cus2 = Customer.getInstance();
System.out.println(cus1 == cus2);//返回true
}
}
class Customer{
//构造函数设为私有 不允许外部实例化
private Customer() {
}
//将自身实例化为一个对象
private static Customer instance = new Customer();
//使用static修饰返回实例
public static Customer getInstance() {
return instance;
}
}
1.2 懒汉模式实现
类Person被加载不会初始化instance,而是需要使用的时候才会初始化;
注:此代码为未考虑线程时的代码,学过线程后会回来更新
public class SingleetonTest2 {
public static void main(String[] args) {
Person p1 = Person.getInstance();
Person p2 = Person.getInstance();
System.out.println(p1 == p2);//返回true
}
}
class Person{
//构造函数设为私有 不允许外部实例化
private Person(){
}
//使用static声明一个属性并赋空值
private static Person instance = null;
public static Person getInstance() {
if(instance == null) {
//判断后实例化 避免多次实例化
instance = new Person();
}
return instance;
}
}
总结
1.饿汉就是类一旦加载,就把单例初始化完成,保证getInstance的时候,单例是已经存在的了,加载时间较短,某些特定的条件下耗费内存2.懒汉比较懒,只有当调用getInstance的时候,才回去初始化这个单例,第一次加载时间较长,后续则相同,某些特定的条件下节省内存。