1.单例模式的定义
单例模式的定义:一个类有且仅有一个实例,并且自行实例化向整个系统提供。
2.单例模式的写法
/**
* 单例模式分为两种(singleton)
* 1.饿汉模式
* */
public class Singleton1 {
//1.将构造方法私有化,在外部无法创建该对象实例
private Singleton1(){
};
//2.在类的内部创建类的实例
private static Singleton1 instance=new Singleton1();
//3.提供一个用于获取实例的方法
public static Singleton1 getInstance(){
return instance;
}
}
/**
* 单例模式分为两种(singleton)
* 1.懒汉模式
* */
public class Singleton2 {
//1.将构造方法私有化,在外部无法创建该对象实例
private Singleton2(){};
//2.在类的内部创建类的实例
private static Singleton2 instance ;
//3.提供一个用于获取实例的方法
public static Singleton getInstance(){
if(instance==null){
instance=new Singleton2();
}
return instance;
}
}
3.饿汉模式与懒汉模式的区别
1.饿汉模式是属于线程安全的,而懒汉模式是非线程安全的。
2.饿汉模式类加载较慢,运行时获取对象速度较快(在第一次加载的时候就创建了一个静态对象供使用)。懒汉模式类加载速度较快,但是运行时获取对象速度较慢。
4.懒汉模式优化
package singleton;
/**通过内部类来解决懒汉模式线程安全问题*/
public class Singleton3 {
private Singleton3(){
};
private static class Singleton3Facotry{
private static Singleton3 instance=new Singleton3();
}
public static Singleton3 getInstance(){
return Singleton3Facotry.instance;
}
}
每日一篇,坚持坚持,是学习的过程,同时记录给自己看!