Gang of Four Creational pattern: Singleton
A class of which only a single instance can exist. Ensure a class only has one instance, and provide a global point of access to it.
The Singleton ensures that only one copy of an instance exists in the same classloader.
package com.javaspeak.designpatterns.go4.creational.singleton;
/**
* Text book description:
* <ul>
* Singleton: A class of which only a single instance can exist. Ensure a class only has one
* instance, and provide a global point of access to it.
* </ul>
* The Singleton ensures that only one copy of an instance exists in the same classloader.
*
* @author John Dickerson - 22 Feb 2020
*/
public class SingletonApplication {
/**
* Retrieves instance from singleton; builds the square and draws it
*/
public void drawSquare() {
ShapeManager.getInstance().buildSquare().draw();
}
public static void main( String[] args ) {
SingletonApplication application = new SingletonApplication();
application.drawSquare();
}
}
package com.javaspeak.designpatterns.go4.creational.singleton;
/**
* @author John Dickerson - 24 Feb 2020
*/
public abstract class Shape {
protected String pixels;
public void draw() {
System.out.println( pixels );
}
}
package com.javaspeak.designpatterns.go4.creational.singleton;
/**
* This class is a singleton. It has a private constructor so it cannot be instantiated directly
* by other classes. Instead it has a static block which initializes the instance which can then
* be retrieved using a static getInstance() method.
* <p>
* Once the instance has been retrieved the buildSquare() method can be called on the instance.
*
* @author John Dickerson - 24 Feb 2020
*/
public class ShapeManager {
private final static ShapeManager instance;
static {
// static block used for initialization
instance = new ShapeManager();
}
/**
* Private constructor
*/
private ShapeManager() {
}
/**
* This method provides the only access to an instance of ShapeManager
*
* @return instance of ShapeManager
*/
public static ShapeManager getInstance() {
return instance;
}
/**
* Instance method
*
* @return
*/
public Square buildSquare() {
return new Square();
}
}
package com.javaspeak.designpatterns.go4.creational.singleton;
/**
* Square
*
* @author John Dickerson - 24 Feb 2020
*/
public class Square extends Shape {
/**
* Constructor pretending to do some expensive initialisation
*/
public Square() {
StringBuilder sb = new StringBuilder();
sb.append( "xxxx\n" );
sb.append( "x x\n" );
sb.append( "x x\n" );
sb.append( "xxxx\n" );
this.pixels = sb.toString();
}
}
Back: Gang of Four
Page Author: JD