Below is a Singleton that I designed as a piece of sample code for a website I'm working on for fun. The goal is to use the Singleton to hold an Earth
object since Earth is unique and there is only 1 of them. Please let me know your thoughts on the implementation.
Singleton.java
package design.patterns;
/**
* This class is a Singleton, we can only have 1 instance of it no matter what!
*
* We mark the class final so that no other classes try to extend it. Some
* designs would want the Singleton to be extendable but we do not!
*/
public final class Earth {
// A static instance of an Earth object
private static Earth earth;
// Some earthly variables
private long ageInYears = 4500000000L;
private float daysForFullOrbit = 365.26f;
private float degreesOfAxisTilt = 23.4f;
private long population = 7046000000L;
// Prevent client from instantiating new Earth objects
private Earth() {
}
/**
* Global access point (no pun intended :)
*
* Synchronized so its thread safe.
*/
public static synchronized Earth getInstance() {
// "Lazy load" an Earth Object
if (earth == null) {
earth = new Earth();
}
return earth;
}
// Basic getters and setters
public double getAgeInYears() {
return ageInYears;
}
public void setAgeInYears(long ageInYears) {
this.ageInYears = ageInYears;
}
public float getdaysForFullOrbit() {
return daysForFullOrbit;
}
public void setdaysForFullOrbit(float daysForFullRotation) {
this.daysForFullOrbit = daysForFullRotation;
}
public float getDegreesOfAxisTilt() {
return degreesOfAxisTilt;
}
public void setDegreesOfAxisTilt(float degreesOfAxisTilt) {
this.degreesOfAxisTilt = degreesOfAxisTilt;
}
public double getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
public static void setEarth(Earth earth) {
Earth.earth = earth;
}
}
Client.java
package design.patterns;
public class Client {
public static void main(String args[]){
Earth earth = Earth.getInstance();
//Invoke Earth's methods from the instance created on line 7
System.out.printf("Earth is over %1$,.0f Days old. \n", earth.getAgeInYears());
//Invoke Earth's methods from the Singleton directly
System.out.println("Earth's orbit takes " + Earth.getInstance().getdaysForFullOrbit() + " days to complete.");
//Invoke Earth's methods both ways
System.out.println("Earth sits on a " + earth.getDegreesOfAxisTilt() + " degree tilt.");
System.out.printf("As of 1/20/2014, there are %1$,.0f people on Earth!", + Earth.getInstance().getPopulation());
}
}