本文介绍了Java 5以来最好的单例模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



由于Java 5,所以创建单例的最佳方式是单元素枚举类型。

  public enum SuperSingleton实现Zooma {
INSTANCE;

/ **
* /
public void fightTheBattle(){
System.out.println(我正在战斗!!!);
}

@Override
public void runningWild(){
//这是从Zooma界面实现的方法。
}
}

根据Joshua Bloch的单元素枚举类型单身是;




  • 更简洁

  • 免费提供序列化机器

  • ,并为多个实例提供一个铁包。



我可以看到它更简洁,它如何提供铁包对于多个实例化,
但是如何免费提供序列化机制?



是单身人士通过成为一个枚举?

解决方案

是的,枚举都是从,实现可序列化


Since Java 5 it is said that the best way to create a singleton is by a single-element enum type.

Example:

public enum SuperSingleton implements Zooma{
    INSTANCE;

    /**
     */
    public void fightTheBattle(){
        System.out.println("I am fighting the battle!!!");
    }

    @Override
    public void runningWild() {
        //This is method implemented from the Zooma interface.      
    }
}

According to Joshua Bloch, the single-element enum type singleton is;

  • more concise
  • provides the serialization machinery for free
  • and provides an ironclad against multiple instantiation.

I can see how it is more concise and how it provides an ironclad against multiple instantiation, but how does it provide the serialization machinery for free?

Is it something the singleton gets by being an enum?

解决方案

Yes, Enums are all extended off of the Enum class, which implements Serializable.

这篇关于Java 5以来最好的单例模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 20:47