I have this class that I use as a singleton this way:
FlagOfficer.instance().someVariable
Here is the current implementation of the class:
public class FlagOfficer {
public FlagOfficer() {
}
static FlagOfficer flagOfficer = null;
public static FlagOfficer instance() {
if (flagOfficer == null) {
flagOfficer = new FlagOfficer();
}
return flagOfficer;
}
public boolean getLastBackupDate;
public boolean syncProcessStartedOnce;
}
I am right now reading the "Effective Java" book where they say the best way to implement the singleton pattern is to use single-element enum type
Here is an example form the book:
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}
So how do I transform my class so that it uses this pattern? And how do I use it afterwards?
public enum FlagOfficer {
// Enum instances/values should be declared first.
// Use INSTANCE(arg1, ..) if constructor accepts agruments.
INSTANCE;
// Constructor can accept arguments as well.
private FlagOfficer() {
}
private Date lastBackupDate;
private boolean syncProcessStartedOnce;
public Date getLastBackupDate() {
return lastBackupDate;
}
public boolean isSyncProcessStartedOnce() {
return syncProcessStartedOnce;
}
}
Usage:
FlagOfficer fo = FlagOfficer.INSTANCE;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With