单例模式(确保对象的唯一性)
程序员文章站
2022-07-14 08:06:40
...
饿汉式,先初始化对象
class Student{
private int age;
private Student(){}
private final static Student s = new Student(); //加了final staitic 的属性不可以被改变
public static Student getInstance(){
return s;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return this.age;
}
}
public class Demo{
public static void main(String[] args){
Student s = Student.getInstance();
Student s1 = Student.getInstance();
s.setAge(20);
System.out.println(s1.getAge());
}
}
懒汉式,第二种是对象是被调用时,才初始化,也叫做对象的延时加载
class Student{
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
private Student(){}
private static Student s = null;
public static Student getInstance(){ //synchronized
if(s==null) //判断是否已经存在
synchronized(Student.class){
if(s==null)
s = new Student();
}
return s; //返回对象
}
}
public class Demo{
public static void main(String[] args){
Student s = Student.getInstance();
Student s1 = Student.getInstance();
s.setAge(20);
System.out.println(s1.getAge());
}
}