代码拉取完成,页面将自动刷新
//单例:有时我们需要某个类保留一个对象,不希望有更多对象,就考虑单例模式
//特点:
//1.单例模式只能有一个实例
//2.单例类必须创建自己的唯一实例
//3.单例类必须向其他对象提供这一实例
//单例的几种实现
//1.饿汉单例
class Singleton{
private Singleton() {}
private final static Singleton SINGLETON = new Singleton();
public static Singleton getInstance() {
return SINGLETON;
}
}
//2.懒汉单例,线程不安全
class Singleton2{
private static Singleton2 instance;
private Singleton2() {}
public static Singleton2 getInstance() {
if(instance ==null) {
instance = new Singleton2();
}
return instance;
}
}
//3.懒汉单例,线程安全(在方法上加一次琐)
class Singleton3{
private static Singleton3 instance;
private Singleton3(){}
public static synchronized Singleton3 getInstance() {
if(instance == null) {
instance = new Singleton3();
}
return instance;
}
}
//懒汉单例,线程安全(静态内部类)
//使用静态内部类,内部类不会在类加载的时候加载,而是在调用getInstance()方法时加载;
class Singleton4{
private static class SingletonInner{
private static Singleton4 instance = new Singleton4();
}
private Singleton4() {}
public static Singleton4 getInstance() {
return SingletonInner.instance;
}
}
//单例,线程安全(枚举)
enum Singleton5{
INSTANCE;
//加其他方法,这种写法调用时,直接Singleton5.INSTANCE.方法
}
//单例,双重校验锁法
class Singleton6{
private static Singleton6 instance;
private Singleton6() {}
public static synchronized Singleton6 getInstance() {
if(instance == null) {
synchronized (Singleton6.class) {
if(instance == null) {
instance = new Singleton6();
}
}
}
return instance;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。