Java. Singleton Pattern


package review;

class Person {
	double r;
	private static Person p1;// 2. Use a private, static variable to reference the instance;

	public double getR() {
		return r;
	}

	private Person() {// 1. Constructor private
		r = Math.random() * 10;
	}

	// 3. Provide a public, static method to get the instance.
	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);
	}
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326991767&siteId=291194637