单例模式:使用枚举版本 [英] Singleton Pattern: Using Enum Version
本文介绍了单例模式:使用枚举版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不明白如何实现 Singleton
模式的枚举
版本。以下是使用Singleton模式实施传统方法的示例。我想更改它以使用枚举版本,但我不知道如何。
I do not understand how to implement the Enum
Version of the Singleton
pattern. Below is an example of implementing "traditional" approach using the Singleton pattern. I would like to change it to use the Enum version but I am not sure how.
public class WirelessSensorFactory implements ISensorFactory{
private static WirelessSensorFactory wirelessSensorFactory;
//Private Const
private WirelessSensorFactory(){
System.out.println("WIRELESS SENSOR FACTORY");
}
public static WirelessSensorFactory getWirelessFactory(){
if(wirelessSensorFactory==null){
wirelessSensorFactory= new WirelessSensorFactory();
}
return wirelessSensorFactory;
}
}
推荐答案
public enum WirelessSensorFactory {
INSTANCE;
// all the methods you want
}
这里是你的单例:只有一个实例的枚举。
Here's your singleton: an enum with only one instance.
请注意,这个单例是线程安全的,而你的不是:两个线程可能都进入竞争条件或可见性并且都创建了自己的单例实例。
Note that this singleton is thread-safe, while yours is not: two threads might both go into a race condition or visibility problem and both create their own instance of your singleton.
这篇关于单例模式:使用枚举版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文