【CSDN常见问题解答】Java单例模式分析

今天中午闲着没事,就随便写点关于Java单例模式的。其实单例模式实现有很多方法,这里我将对这些方法进行对比分析:

第一种:

public class Singleton2 {
	
	private Singleton2(){
		System.out.println("This is Singleton2's instance.");
	};
	
	private static Singleton2 instance = null;
	
	public static Singleton2 getInstance(){
		if(instance == null) {
			instance = new Singleton2();
		}
		return instance;
	}
}

这种情况未加锁,可能会产生数据错误,比如两个同时新生成的对象,一个把对象数据改变了,而另一个使用的没改变之前的。

第二种:

public class Singleton1 {
	
	private Singleton1(){
		System.out.println("This is Singleton1's instance.");
	}
	
	private static Singleton1 instance = null;

	public static Singleton1 getInstance2() {
		if(instance == null){   //1
			synchronized (Singleton1.class) {  //2
				if(instance == null) {
					instance = new Singleton1();
				}
			}
		}
		return instance;
	}
	
}

这种只会在第一次的时候产生阻塞,之后每实例一次对象,就会在第1步时跳过去,在第一次实例的时候,会在第2步那里产生阻塞,以后就不会了,这种相对来说是最好的。

第三种:

public class Singleton1 {
	
	private Singleton1(){
		System.out.println("This is Singleton1's instance.");
	}
	
	private static Singleton1 instance = null;
	
	public static synchronized Singleton1 getInstance(){  //1
		
		if(instance == null){
			instance = new Singleton1();
		}
		return instance;
	}
}

多线程的时候每次都会在1这里产生阻塞。



Java中的单例模式是指一个类只有一个实例,且该类能自行创建这个实例的一种模式。在Java中,单例模式可以通过不同的实现方式来实现,其中一种常见的实现方式是使用静态工厂方法模式(Simple Factory Pattern)。静态工厂方法模式是一种创建型模式,它通过一个静态方法来创建对象,而不是通过直接调用构造方法来创建对象。这种模式可以将对象的创建和使用解耦,提供了一种更加灵活和可控的方式来实现对象的创建。工厂模式是Java中常用的设计模式之一,它属于创建型模式,提供了一种创建对象的最佳方式。工厂模式通过定义一个共同的接口或抽象类来创建对象,然后由具体的工厂类来实现这个接口或抽象类,并负责创建具体的对象。这样一来,客户端就可以通过工厂类来创建对象,而无需直接调用对象的构造方法。 [1][2][3<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [基于java单例模型和工厂模式](https://blog.csdn.net/weixin_56102526/article/details/120318486)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值