(1)概念
设计模式的概念:解决开发中某些特定问题的固定写法
单例:单个实例,整个应用中有且只有一个该类的对象
(2)步骤
1.构造函数私有化
2.在本类中创建本类的对象
3.对外提供一个获取本类对象的静态方法
(3)饿汉式
// 饿汉式
public class Singleton1 {
private static Singleton1 singleton1 = new Singleton1();
private Singleton1(){}
public static Singleton1 getInstance(){
return singleton1;
}
}
(4)懒汉式
// 懒汉式
public class Singleton2 {
private Singleton2(){}
private static Singleton2 singleton2 = null;
public static Singleton2 getInstance(){
if(singleton2 == null){
singleton2 = new Singleton2();
}
return singleton2;
}
}
(5)饿汉式和懒汉式的区别:
1.对象创建的时机不同:饿汉式是在类加载时就创建了对象;懒汉式只有在调用 getInstance() 时才创建对象
2.对于饿汉式来说,没有调用 getInstance() 方法时对象也会创建,占用资源
3.懒汉式线程不安全
// 懒汉式
public class Singleton2 {
private Singleton2(){}
private static Singleton2 singleton2 = null;
public static synchronized Singleton2 getInstance(){
if(singleton2 == null){
singleton2 = new Singleton2();
}
return singleton2;
}
}