懒汉式和饿汉式都是讲单例设计模式的时候涉及的内容:
饿汉式是先初始化对象,饿汉式类一进内存,就创建对象,设计一般建议饿汉式;而懒汉式,延迟加载,调用相应方法时,才建立对象,下面举个例子说明:
Eg: class SimpleDemo//单例设计模式
{
public static void main(String[] args)
{
Student s1=Student.getInstance();
Student s2=Student.getInstance();
s1.setAge(20);
s1.setName("HuangQin");
System.out.println(s2.getAge()+";"+s2.getName());
}
}
class Student
{
private String name;
private int age;
public void setAge(int age)
{
this.age=age;
}
public int getAge()
{
return age;
}
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
private Student(){}
public static Student s=new Student();//先初始化对象,称为:饿汉式----类一进内存,就创建对象
public static Student getInstance()
{
return s;
}
}
/* class Student
{
private static Student s=null;//懒汉式,延迟加载,调用getInstance方法时,才建立对象
private Student(){}
public static Student getInstance()
{
if(s==null)
s=new Studente();
return s;
}
}
*/ |