首先说下单例,单例其实就是单个实例,也就是全局只有一个实例对象。分析下它的优缺点:
优点
(1) 由于单例模式在内存中只有一个实例,减少内存开支,特别是一个对象需要频繁地创建销毁时,而且创建或销毁时性能又无法优化,单例模式就非常明显了
(2) 由于单例模式只生成一个实例,所以,减少系统的性能开销,当一个对象产生需要比较多的资源时,如读取配置,产生其他依赖对象时,则可以通过在应用启动时直接产生一个单例对象,然后永久驻留内存的方式来解决。
(3) 单例模式可以避免对资源的多重占用,例如一个写文件操作,由于只有一个实例存在内存中,避免对同一个资源文件的同时写操作
(4) 单例模式可以在系统设置全局的访问点,优化和共享资源访问,例如,可以设计一个单例类,负责所有数据表的映射处理。
缺点
(1) 单例模式没有抽象层,扩展很困难,若要扩展,除了修改代码基本上没有第二种途径可以实现。
(2) 单例类的职责过重,在一定程度上违背了“单一职责原则”。
(3) 滥用单例将带来一些负面问题,如:为了节省资源将数据库连接池对象设计为的单例类,可能会导致共享连接池对象的程序过多而出现连接池溢出;
又比如:在多个线程中操作单例类的成员时,但单例中并没有对该成员进行线程互斥处理。
使用注意事项:
1.使用时不能用反射模式创建单例,否则会实例化一个新的对象
2.使用懒单例模式时注意线程安全问题
3.饿单例模式和懒单例模式构造方法都是私有的,因而是不能被继承的,有些单例模式可以被继承(如登记式模式)
饿汉:
/**
* 饿汉式单例(提前把对象创建)
* 可能会浪费空间,提前把对象创建好了,但是不一定会用。
* 但是它是线程安全的
*/
public class Hungry {
//构造方法私有
private Hungry(){
}
//final实例化一个私有的对象
//两个private保证了在其他地方不能实例化对象
private final static Hungry HUNGRY=new Hungry();
//通过静态方法,暴露实例到全局
public static Hungry getInstance(){
return HUNGRY;
}
}
懒汉式:
单线程下可用,多线程下不可用,存在多线程并发问题。
/**
* 懒汉式单例(当使用时再创建对象)
* 单线程下可用
*/
public class LazyMan {
private LazyMan(){
}
private static LazyMan lazyMan;
public LazyMan getInstnce(){
//多个线程同时到这里,都进这个if,可以有多个实例
if(lazyMan==null){
lazyMan=new LazyMan();
}
return lazyMan;
}
}
用多线程并发测试:(多次运行,查看打印结果,会发现个别有不同的实例)
public class LazyMan {
private LazyMan(){
System.out.println(Thread.currentThread().getName()+"ok");
}
private static LazyMan lazyMan;
public static LazyMan getInstance(){
if(lazyMan==null){
lazyMan=new LazyMan();
}
return lazyMan;
}
//多线程并发测试
public static void main(String[] args){
for(int i=0;i<10;i++){
new Thread(()->{
lazyMan.getInstance();
}).start();
}
}
}
于是进阶为(加锁)DCL懒汉式(成为双重检测锁模式):
public class LazyMan {
private LazyMan(){
System.out.println(Thread.currentThread().getName()+"ok");
}
private static LazyMan lazyMan;
//双重检测锁模式的懒汉式单例,DCL懒汉式
public static LazyMan getInstance(){
if(lazyMan==null){
synchronized (LazyMan.class){
if(lazyMan==null){
lazyMan=new LazyMan();
}
}
}
return lazyMan;
}
//多线程并发测试
public static void main(String[] args){
for(int i=0;i<10;i++){
new Thread(()->lazyMan.getInstance()
).start();
}
}
}
每一个线程开启,都只是同一个单例对象。
DCL懒汉式单例再改进(添加volatle消除指令重排):
public class LazyMan {
private LazyMan(){
System.out.println(Thread.currentThread().getName()+"ok");
}
private volatile static LazyMan lazyMan;
//双重检测锁模式的懒汉式单例,DCL懒汉式
public static LazyMan getInstance(){
if(lazyMan==null){
synchronized (LazyMan.class){
if(lazyMan==null){
lazyMan=new LazyMan();//不是原子性操作
/**不是原子性操作会发生以下三操作
* 1.分配内存空间
* 2.执行构造方法,初始化对象
* 3.把这个对象指向这个空间
*
*
* 会导致123或132顺序执行
* 若A线程顺序是132,又来了一个B线程,
* 则此时lazyMan没有完成构造,则会发生问题。(指令重排)
*/
}
}
}
return lazyMan;
}
//多线程并发测试
public static void main(String[] args){
for(int i=0;i<10;i++){
new Thread(()->lazyMan.getInstance()
).start();
}
}
}
静态内部类单例:
/**
* 静态内部类
*/
public class Holder {
private Holder(){
}
public static Holder getInstance(){
return InnerClass.HOLDER;
}
public static class InnerClass{
private static final Holder HOLDER=new Holder();
}
}
以上单例方法都有问题,因为存在反射技术!!!
演示反射破解(两重检测锁模式)DCL进阶版懒汉式:
//反射
public static void main(String[] args) throws Exception {
LazyMan instance1 = LazyMan.getInstance();
Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
declaredConstructor.setAccessible(true);
LazyMan instance2 = declaredConstructor.newInstance();
System.out.println(instance1);
System.out.println(instance2);
}
进阶:在无参构造器中进行判断(成为三层检测锁模式),再执行,
判断,抛异常来保证实例只有一个:
public class LazyMan {
private LazyMan(){
synchronized (LazyMan.class){
if(lazyMan!=null){
throw new RuntimeException("不要试图使用反射破坏异常");
}
}
}
private volatile static LazyMan lazyMan;
//双重检测锁模式的懒汉式单例,DCL懒汉式
public static LazyMan getInstance(){
if(lazyMan==null){
synchronized (LazyMan.class){
if(lazyMan==null){
lazyMan=new LazyMan();//不是原子性操作
/**不是原子性操作会发生以下三操作
* 1.分配内存空间
* 2.执行构造方法,初始化对象
* 3.把这个对象指向这个空间
*
*
* 会导致123或132顺序执行
* 若A线程顺序是132,又来了一个B线程,
* 则此时lazyMan没有完成构造,则会发生问题。
*/
}
}
}
return lazyMan;
}
//反射
public static void main(String[] args) throws Exception {
LazyMan instance1 = LazyMan.getInstance();
Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
declaredConstructor.setAccessible(true);
LazyMan instance2 = declaredConstructor.newInstance();
System.out.println(instance1);
System.out.println(instance2);
}
}
从这里开始可能是我的理解还不到位,只能是先保留收藏
使用反射再次破解时,把两个对象都用反射的方法newInstance() 创建出来:
//反射
public static void main(String[] args) throws Exception {
// LazyMan instance1 = LazyMan.getInstance();
Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
declaredConstructor.setAccessible(true);
LazyMan instance1 = declaredConstructor.newInstance();
LazyMan instance2 = declaredConstructor.newInstance();
System.out.println(instance1);
System.out.println(instance2);
}
进阶:采用红路灯(添加muzi属性),再执行:
public class LazyMan {
private static boolean muzi=false;
private LazyMan(){
synchronized (LazyMan.class){
if(muzi==false){
muzi=true;
} else{
throw new RuntimeException("不要试图使用反射破坏异常");
}
}
}
private volatile static LazyMan lazyMan;
//双重检测锁模式的懒汉式单例,DCL懒汉式
public static LazyMan getInstance(){
if(lazyMan==null){
synchronized (LazyMan.class){
if(lazyMan==null){
lazyMan=new LazyMan();//不是原子性操作
/**不是原子性操作会发生以下三操作
* 1.分配内存空间
* 2.执行构造方法,初始化对象
* 3.把这个对象指向这个空间
*
*
* 会导致123或132顺序执行
* 若A线程顺序是132,又来了一个B线程,
* 则此时lazyMan没有完成构造,则会发生问题。
*/
}
}
}
return lazyMan;
}
//反射
public static void main(String[] args) throws Exception {
// LazyMan instance1 = LazyMan.getInstance();
Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
declaredConstructor.setAccessible(true);
LazyMan instance1 = declaredConstructor.newInstance();
LazyMan instance2 = declaredConstructor.newInstance();
System.out.println(instance1);
System.out.println(instance2);
}
}
反射破解(通过反射获取muzi属性,并修改):
//反射
public static void main(String[] args) throws Exception {
// LazyMan instance1 = LazyMan.getInstance();
Field muzi = LazyMan.class.getDeclaredField("muzi");
muzi.setAccessible(true);
Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
declaredConstructor.setAccessible(true);
LazyMan instance1 = declaredConstructor.newInstance();
muzi.set(instance1,false);
LazyMan instance2 = declaredConstructor.newInstance();
System.out.println(instance1);
System.out.println(instance2);
}
枚举
/**
* 枚举
*/
public enum EnumSingle {
INSTANCE;
public EnumSingle getInstance(){
return INSTANCE;
}
}
上面是自己学习单例总结内容,单例看似简单的设计模式,其实用好了还是有难度的,我学习之后还有部分不是很了解,希望在今后自己水平提升之后能更好的理解单例模式。