`
android2116
  • 浏览: 14083 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

JAVA实现单例设计模式(Single patterns)代码

阅读更多
/*
单例设计模式:一个类中只存在一个对象的模式。
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

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics