设计模式之单例设计模式(饿汉式)
来源:互联网 发布:qq api 发送消息 java 编辑:程序博客网 时间:2024/06/08 02:15
//饿汉式:类一加载就创建
//创建单例对象package july.star.thread22; /** * Student * 创建单例对象 * @author MoXingJian * @email 939697374@qq.com * @date 2016年12月10日 下午8:42:31 * @version 1.0 */public class Student { //构造方法私有 private Student(){ } //自己造一个对象 //静态方法调用成员变量,成员变量也要为静态的 private static Student s = new Student(); //提供公共的访问方式 //要使外部直接调用,需要变为静态 public static Student getStudent(){ return s; }}
//测试package july.star.thread22;/** * StudentDemo * 单例设计模式 * @author MoXingJian * @email 939697374@qq.com * @date 2016年12月10日 下午8:44:24 * @version 1.0 */import org.omg.Messaging.SyncScopeHelper;/** * * 单例模式:保证类在内存中只有一个对象 * * 如何保证在内存中只有一个对象 A:构造方法私有 B:在成员变量位置自己创建一个对象 C:提供对外访问的接口 */public class StudentDemo { public static void main(String[] args) { // 以前创建对象的方式 /*Student s1 = new Student(); Student s2 = new Student(); System.out.println(s1 == s2);*/ // false 因为创建了两个对象 //外部赋值篡改值,防止该事情发生在对象中将成员变量私有 //Student.s = null; //单例模式 Student s1 = Student.getStudent(); Student s2 = Student.getStudent(); System.out.println(s1 == s2); //true System.out.println(s1); System.out.println(s2); /** * 输出结果 * true * july.star.thread22.Student@8bfc25c * july.star.thread22.Student@8bfc25c */ }}
0 0
- 设计模式之单例设计模式(饿汉式)
- 设计模式之单例设计模式(饿汉单例设计模式&懒汉单例设计模式)
- 设计模式之单例模式饿汉式
- 设计模式之(单例模式)
- 设计模式之(单例模式)
- 设计模式之 单例设计模式
- 设计模式之 单例设计模式
- 设计模式之单例设计模式
- 设计模式之-----------单例设计模式
- 设计模式之:单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- Atitti 存储引擎支持的国内点与特性attilax总结
- 【CSS+DIV】CSS基本概念和4种控制页面方法
- 中间人攻击之---ARP欺骗
- Azkaban实例的配置文件
- Python学习笔记(7)-函数
- 设计模式之单例设计模式(饿汉式)
- Python 使用xlrd读Excel文件报错
- maven项目中添加本地jar包
- javascript学习之判断字符串
- HDU-3191-How Many Paths Are There
- nyoj 737 石子合并 经典区间 dp
- 数据结构实验之排序五:归并求逆序数
- java.lang.NumberFormatException: null原因
- 【55.70%】【codeforces 557A】Ilya and Diplomas