Java.单例模式



package review;

class Person {
double r;
private static Person p1;// 2.用一个私有、静态变量引用实例;

public double getR() {
return r;
}

private Person() {// 1.构造器私有
r = Math.random() * 10;
}

// 3.提供一个公有、静态方法获得实例。
public static Person getPerson() {
if (p1 == null) {
p1 = new Person();
}
return p1;
}
}

public class T7 {
public static void main(String[] args) {
Person p1 = Person.getPerson();
Person p2 = Person.getPerson();
int r = (int) p1.getR();
int r2 = (int) p2.getR();
System.out.println(r);
System.out.println(r2);
}
}

;