单例设计模式
public class Singleton {
private Singleton() {};
private static Singleton singleton = new Singleton();
public static Singleton getInstance() {
return singleton;
}
}
单例模式保证内存中的对象唯一
private,为了避免其他程序过多建立该类对象。先禁止其他程序建立该类对象
static ,还为了让其他程序可以访问到该类对象,只好在本类中,自定义一个对象。
getSingle,为了方便其他程序对自定义对象的访问,可以对外提供一些访问方式。
应用例子
class Student
{
private int age;
private static Student s = new Student();
private Student(){}
public static Student getStudent()
{
return s;
}
public void setAge(int age)
{
this.age = age;
}
public int getAge()
{
return age;
}
}