I want to coordinate a state across my system. For this purpose, I create a class for my state.
How do I make sure there is always only one instance of my State class in my system?
public class WifiState {
private int numberOfClients;
private int mbDownloadVolume;
private int mbUploadVolume;
public WifiState() {}
// setters
}
// ...somewhere in code...
// State state = new WifiState();
// state.setNumberOfClients(30);
// ...
// ...somewhere in code...
// How do I get the current state?
Gang of Four: "Ensure a class only has one instance, and provide a global point of access to it."
Wikipedia: "Design pattern that restricts the instantiation of a class to one 'single' instance. This is useful when exactly one object is needed to coordinate actions across the system."
public class WifiState {
private int numberOfClients;
private int mbDownloadVolume;
private int mbUploadVolume;
public WifiState() {}
// setters
}
public class WifiState {
private static WifiState INSTANCE;
private int numClients = 0;
private int mbDownloadRate = 0;
private int mbUploadRate = 0;
private WifiState() {}
public static WifiState getInstance() {
if (INSTANCE == null) {
INSTANCE = new WifiState();
}
return INSTANCE;
}
}
/**
* Represents a log of alarm system events.
* We use the Singleton Design Pattern to ensure that there is only
* one EventLog in the system and that the system has global access
* to the single instance of the EventLog.
*/
public class EventLog implements Iterable<Event> {
Highlander (THE ONE HIGHLANDER):
/>___________________________________
[########[]_________________________________/
/>
Highlander (THE ONE HIGHLANDER):
/>___________________________________
[########[]_________________________________/
/>
Desired Output
Highlander (Joe's Highlander):
/>___________________________________
[########[]_________________________________/
/>
Highlander (Sue's Highlander):
/>___________________________________
[########[]_________________________________/
/>
Actual Output