编写一个延迟加载的单例设计模式
public class Test8{
static class People{
private String name;
private String sex;
private int age;
//构造方法私有化,只能子在本类中对此类进行实例对象,
//在其他的类中不能对类进行实例化,然后通过创建方法返回在本类中实例的对象。这就是单例设计模式。
private People(String name,String sex,int age)
{
super();
this.name=name;
this.sex=sex;
this.age=age;
}
public People()
{
}
public static People p=null;
//首先给声明一个对象,,但是实例化,给其一个空值。
public static People getPeople(){
synchronized (People.class){
if(p==null){
p=new People();
//在方法中对声明的对象,进行实例化,在判断条件成立的前提下。只要类一加载,
//对象不会实例化,必须调用获得对象的方法才能实例化此对象,这就是延迟加载。
}
}
return p;
}
public String toString()
{
return "姓名:"+name+" 性别: "+sex+" 年龄: "+age;
}
}
public static void main(String[] args)
{
People p1=People.getPeople();
People p2=People.getPeople();
People p3=People.getPeople();
p1=new People("王五","男",22);
p2=new People("赵敏","女",20);
p3=new People("张三","男",21);
System.out.println(p1);
System.out.println(p2);
System.out.println(p3);
}
}
|