单例模式

单例模式(Singleton Pattern)在java中算是最常用的设计模式之一,主要用于控制控制类实例的数量,防止外部实例化或者修改。单例模式在某些场景下可以提高系统运行效率。实现中的主要特点有以下三点:

  1. 私有构造函数(private constructor):其他的类不能实例化此类的对象。
  2. 私有化引用(private reference): 类之外不能修改。
  3. 存在唯一的实例化对象的静态方法。

下面以美国只有一个总统的例子对单例模式进行形象化说明。

类图

代码

 package patterns;

 public class AmericaPresident {

     private static AmericaPresident aAmericaPresident;

     private AmericaPresident(){}

     public static AmericaPresident getAmericaPresidentInstance(){
if(aAmericaPresident == null)
aAmericaPresident = new AmericaPresident();
return aAmericaPresident;
} public static void testAmericanPresidentInstance(){
System.out.println(aAmericaPresident.hashCode());
} public static void main(String[] args){
AmericaPresident americaPresident_1 = AmericaPresident.getAmericaPresidentInstance();
americaPresident_1.testAmericanPresidentInstance();
AmericaPresident americaPresident_2 = AmericaPresident.getAmericaPresidentInstance();
americaPresident_2.testAmericanPresidentInstance();
}
}

输出

580487944

580487944

结论

两次实例化的对象的哈西直相同,说明第二次实例化的事后没有真正的进行实例化,返回的是第一次实例化的对象。

最新文章

  1. mysql获取一个表中的下一个自增(id)值的方法
  2. CString 操作
  3. 控制Wordpress对搜索引擎的可见性
  4. git 创建分支并切换
  5. android 6.0 httpclient
  6. React Native 简介:用 JavaScript 搭建 iOS 应用 (1)
  7. VB语言基础
  8. js取一维数组最大值,最小值
  9. Android JNI 编译正确 但是提示程序有错误无法运行 而且还看不到任何错误提示 的解决方法
  10. Html 定位position
  11. Java并发包分析——BlockingQueue
  12. Bloom filter 2
  13. 010-1 Socket地址族AddressFamily
  14. Solve Error : Undefined function or variable ‘setInitialWorkingFolder’. Error in matlabrc (line 197)
  15. sas 配置文件和AutoExec
  16. Linux下DIR,dirent,stat等结构体详解(转)
  17. Kubernetes 1.5 配置dns
  18. GoLang中如何使用多参数属性传参
  19. IndexOf、LastIndexOf、Substring的用法及C# foreach 中获取索引index的方法
  20. es6 入坑笔记(四)---异步处理

热门文章

  1. ubuntu创建、删除文件及文件夹,强制清空回收站方法
  2. zoj 3742 Delivery 好题
  3. MVC Action,Service中筛选int 和list<int>
  4. $(function(){})与$(document).ready(function(){})
  5. .NET DLL 保护措施应用实例(百度云批量保存工具)
  6. PHP面向对象之将数据库的查询结果序列化成json格式
  7. 十二、Android UI开发专题(转)
  8. Ajax的ActionLink方法(适用于异步加载)
  9. 单一职责原则(SRP)
  10. angularjs中的directive