【Java】单例(singleton)设计模式

发布时间:2019-11-17 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了【Java】单例(singleton)设计模式脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

单例设计模式是Java中应用最为广泛的设计模式之一,保证了一个类始终只有一个对象,具有以下特点:

  • 私有的构造函数 ——没有其他的类能实例化该对象
  • 引用时私有的
  • public static方法是获取对象的唯一方式

singleton故事

这里1有一个关于singleton的故事,一个国家只能有且仅有一个PResident,president只能被实例化一次,getPresident()返回这个仅有的president。

public class americaPresident {     private static final AmericaPresident thePresident = new AmericaPresident();      private AmericaPresident() {}      public static AmericaPresident getPresident() {         return thePresident;     } } 

singleton在runtime中的应用

class Runtime {     private static Runtime currentRuntime = new Runtime();      public static Runtime getRuntime() {         return currentRuntime;     }      private Runtime() {}      //...  } 

脚本宝典总结

以上是脚本宝典为你收集整理的【Java】单例(singleton)设计模式全部内容,希望文章能够帮你解决【Java】单例(singleton)设计模式所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。