/*
单例设计模式:一个类中只存在一个对象的模式。
p.s.删除main函数的中注释语句,可以对比运行,加深理解。
*/
class SingleDemo
{
public static void main(String[] args)
{
Student s1 = new Student();
Student s2 = new Student();
s1.setName( "Lily" );
s1.setAge( 20 );
s1.prtStuInfo( s1.getName(), s1.getAge() );
//s2.setName( "Lilei" );
//s2.setAge( 22 );
s2.prtStuInfo( s2.getName(), s2.getAge() );
//===========test Single Design Patterns===========
Student1 stu1 = Student1.getStu1Instace();
Student1 stu2 = Student1.getStu1Instace();
stu1.setName( "Lily" );
stu1.setAge( 20 );
stu1.prtStuInfo( stu1.getName(), stu1.getAge() );
//stu2.setName( "Lilei" );
//stu2.setAge( 22 );
stu2.prtStuInfo( stu1.getName(), stu1.getAge() );
//stu1.prtStuInfo( stu1.getName(), stu1.getAge() );
}//end of mehtod main
}//end of class SingleDemo
class Student
{
private String name;
private int age;
public void setName( String name )
{
this.name = name;
}//end of method setName
public String getName()
{
return name;
}//end of method getName
public void setAge( int age )
{
this.age = age;
}//end of method setAge
public int getAge()
{
return age;
}//end of method getAge
public void prtStuInfo( String name, int age )
{
System.out.println( "Student name:" + name + "\t age:" + age );
}//end of method prtStuInfo
}//end of class Student
class Student1
{
private String name;
private int age;
private static Student1 s = new Student1();//②创建一个私有实例,④静态方法访问,设置静态
private Student1(){}//①私有化构造函数
public static Student1 getStu1Instace()//③提供匿名访问方法
{
return s;
}//end of method getStu1Instance
public void setName( String name )
{
this.name = name;
}//end of method setName
public String getName()
{
return name;
}//end of method getName
public void setAge( int age )
{
this.age = age;
}//end of method setAge
public int getAge()
{
return age;
}//end of method getAge
public void prtStuInfo( String name, int age )
{
System.out.println( "Student1 name:" + name + "\t age:" + age );
}//end of method prtStuInfo
}//end of class Student1
单例设计模式在Java中的应用
本文通过对比实例展示了Java中的单例设计模式,详细介绍了如何在一个类中确保只存在一个对象,以及如何实现这一模式。通过实例操作,深入理解了单例模式的实现方式及其在实际开发中的应用。
1240

被折叠的 条评论
为什么被折叠?



