单例模式代码-面试

恶汉模式:类.属性得到对象

1.

public class Singleton1 {
//为了实现类名.属性,使用static修饰符,final强调唯一
	public static final Singleton1 INTANCE = new Singleton1();
	//既然唯一就不能被调用构造方法创建对象,故私有
	private Singleton1() {
		
	}
}

2.枚举

public enum Singleton2 {
	INSTANCE
}

3.静态代码块:

public class Singleton3 {
	private static final Singleton3 INTANCE ;
	static {
		INTANCE = new Singleton3();
	}
	private Singleton3() {
		
	}
}

懒汉模式:类.方法创建对象

1.单线程

public class Singleton4 {
//不能直接被使用类名.属性调用,避免null,故私有
		private static Singleton4 instance;
		private Singleton4() {
			
		}
		public static Singleton4 getInstance() {
		//空才创建,实现唯一
			if(instance == null) {
				try {
					Thread.sleep(100);
				}catch(Exception e) {
					e.printStackTrace();
				}
				instance = new Singleton4();
			}
			return instance;
		}
}

2.多线程

public class Singleton5 {
	public static Singleton5 instance;
	private Singleton5() {
		
	}
	public static Singleton5 getInstance() {
	//多线程下,线程1执行到if(instance == null) 休眠,instance == null,此时线程2抢占cpu,执行到if(instance == null),instance 还是为null,此时无论哪个执行下去,都会创建两个对象,加锁,一个全部执行完才能让另一个执行
		synchronized(Singleton5.class) {
			if(instance == null) {
				try {
					Thread.sleep(100);
				}catch(Exception e) {
					e.printStackTrace();
				}
				instance = new Singleton5();
			}
		}
		return instance;
	}
}

3.多线程提高效率

public class Singleton6 {
	public static Singleton6 instance;
	private Singleton6() {
		
	}
	public static Singleton6 getInstance() {
	//先判断,提高效率
		if(instance == null) {
			synchronized(Singleton5.class) {
				if(instance == null) {
					try {
						Thread.sleep(100);
					}catch(Exception e) {
						e.printStackTrace();
					}
					instance = new Singleton6();
				}
			}	
		}
		return instance;
	}
}

4.多线程(内部类实现)

public class Singleton7 {
	private Singleton7() {
		
	}
	//内部类加载才会创建对象
	private static class inner{
		private static final Singleton7 INSTANCE = new Singleton7();
	}
	public static Singleton7 getInstance() {
		return inner.INSTANCE;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Fire king

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值