//饿汉式:类一加载就创建
//创建单例对象
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
*/
}
}