Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the "single-element enum type" to make this class a singleton?

Tags:

java

enums

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?

like image 628
Kaloyan Roussev Avatar asked Dec 31 '25 21:12

Kaloyan Roussev


1 Answers

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;
like image 73
nhylated Avatar answered Jan 03 '26 09:01

nhylated



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!