设计模式-----单例模式

单例模式特点:一个类只有一个实例。核心: 私有的构造方法,保证外部类不能通过new创建对象。

具体实现方法:

1 懒汉式(线程不安全)

public class SingletonTest {
	private static SingletonTest singleton;

	private SingletonTest() {
	
	}
	public static SingletonTest getInstance(){
		if(singleton==null){
			singleton=new SingletonTest();
		}
		return singleton;
	}

}

2.懒汉式(线程安全) :在方法上加上synchronized关键字

public class SingletonTest {
	private static SingletonTest singleton;

	private SingletonTest() {
	
	}
	public static synchronized SingletonTest getInstance(){
		if(singleton==null){
			singleton=new SingletonTest();
		}
		return singleton;
	}

}

饿汉式:每次调用都会创建 消耗资源

public class SingletonTest {
	private static SingletonTest singleton=new SingletonTest();;

	private SingletonTest() {
	
	}
	public static synchronized SingletonTest getInstance(){
			singleton=new SingletonTest();
		return singleton;
	}

}
静态内部类:相比饿汉模式,只有在调用getInstance方法才会初始化对象。
public class SingletonTest {
	private SingletonTest() {
		
	}
	public static SingletonTest getInstance(){
		return Singleton.singleton;
	}
	private final static class Singleton{
		private static SingletonTest singleton=new SingletonTest();
	}
}

枚举类

public enum SingletonTest {
    instance;
    public void getInstance(){
    }
}

双重校验锁

public class SingletonTest {
	private volatile static SingletonTest singleton;

	private SingletonTest() {
	
	}
	public static  SingletonTest getInstance(){
		if(singleton==null){
			synchronized(SingletonTest.class){
				singleton=new SingletonTest();
			}
		}
		return singleton;
	}

}
在多线程中可能会有多个线程同时访问,会创建对个实例,所以需要加锁保证单例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值