[置顶]单例设计模式 (代码实现)
来源:互联网 发布:linux配置网络 编辑:程序博客网 时间:2024/06/08 01:29
---单例设计模式之饿汉式---
创建SingleInstance类
1 /** 2 * 单例设计模式之饿汉式 3 */ 4 public class SingleInstance { 5 /** 6 * 私有化构造方法 7 */ 8 private SingleInstance() {} 9 /**10 * 成员变量11 */12 private static SingleInstance instance = new SingleInstance() ;13 /**14 * 提供一个静态的成员方法,返回该对象15 */16 public static SingleInstance getInstance() {17 return instance ;18 }19 }
创建测试类SingleInstanceDemo
1 /** 2 * 单例设计模式的思想: 保证该类在内存中只有一个实例(对象) 3 * 优点节省内存,提高内存利用率 4 */ 5 public class SingleInstanceDemo { 6 7 public static void main(String[] args) { 8 9 // 调用方法获取对象10 SingleInstance instance1 = SingleInstance.getInstance() ;11 SingleInstance instance2 = SingleInstance.getInstance() ;12 13 // 输出14 System.out.println(instance1 == instance2);15 }16 }
-------------------------------------------------------------------------------------------------------------
---单例设计模式之懒汉式---
创建SingleInstance2类
1 /** 2 * 单例设计模式之懒汉式 3 * 4 * 面试中写那种单例设计模式呢? 5 * 面试中写懒汉式: 因为懒汉式体现了两种思想, 第一种线程问题 , 第二种 延迟加载 6 * 7 * 开发中写饿汉式 8 */ 9 public class SingleInstance2 {10 /**11 * 私有化构造方法12 */13 private SingleInstance2() {}14 /**15 * 提供一个成员变量16 */17 private static SingleInstance2 instance = null ;18 /**19 * 提供一个静态的成员方法20 */21 public static synchronized SingleInstance2 getInstance() {22 23 if(instance == null){24 instance = new SingleInstance2() ;25 }26 return instance ;27 }28 }
创建测试类SingleInstanceDemo2
1 public class SingleInstance2Demo { 2 3 public static void main(String[] args) { 4 5 // 获取对象 6 SingleInstance2 instance1 = SingleInstance2.getInstance() ; 7 SingleInstance2 instance2 = SingleInstance2.getInstance() ; 8 9 // 比较10 System.out.println(instance1 == instance2);11 12 }13 14 }
0 0
- [置顶]单例设计模式 (代码实现)
- 设计模式之单例模式(C++代码实现)
- 单例设计模式的实现代码
- 单例模式代码实现(C++)
- 单例模式(C++代码实现)
- 设计模式之单例模式(代码)
- [置顶] 多例设计模式
- 基本设计模式:单例模式和工厂模式代码实现
- AspectJ实现设计模式(六)—单例模式
- AspectJ实现设计模式(六)—单例模式
- 设计模式九(单例模式,python语言实现)
- 设计模式之单例模式(python实现)
- 设计模式实现(十七)---单例模式(SingleTon)
- 设计模式 - 单例模式(Singleton) C++实现
- 设计模式C++实现:单例模式(Singleton)
- 设计模式——单例模式(C++实现)
- 设计模式(一):单例模式 java实现
- 设计模式----单例模式(c++实现)
- [置顶]MySQL 的相关语句(增删改查)(SQLyog软件实现)
- [置顶]XML 概述 (可扩展标记语言)
- [置顶]Java中 实现多线程成的三种方式(继承,实现,匿名内部类)
- [置顶]数据类型转换(面试题)
- [置顶]JDBC快速入门
- [置顶]单例设计模式 (代码实现)
- [置顶]pull解析器: 反序列化与序列化
- struts2出现Could not find action or result的错误原因
- [置顶]Servlet的生命周期+实现方式
- [置顶]Request 和 Response 原理
- [置顶]会话技术( Cookie ,Session)
- [置顶]android 四大组件之---Service
- #CentOS on Mac#4.WebBench测试TinyHttpd
- [置顶]showSetPwdDialog--自定义对话框