2

This is a follow up question after reading answers to this question. Most of people so keen on recommending single element enums over singleton class implementations. For instance:

Singleton with enum:

public enum Singleton{
INSTANCE;
    public void doStuff(){
        //......
    }
    public void doMoreStuff(){
        //......
    }
}

According to Java Docs; An enum type is a special data type that enables for a variable to be a set of predefined constants.

My Question: Pardon me if this is a stupid question. As singletons are capable of maintaining global states for the application, When implementing singletons in with the single element enums, how can you maintain different states with your singleton?

For example If I want my Singleton to keep followings;

public myStringField="";
public int myIntField=0;

How can I do it with single element enums?

Community
  • 1
  • 1
Govinnage Rasika Perera
  • 2,134
  • 1
  • 21
  • 33

2 Answers2

1

Whatever "state" you want as part of singleton should be added to the singleton instance itself. In the example below I have added a String to Singleton "state".

enum Singleton{
INSTANCE("some string");

    private String myString;
    public void doStuff(){
        //......
    }
    public void doMoreStuff(){
        //......
    }

    Singleton (String myString_){
      myString = myString_;
    }
}
SJha
  • 1,510
  • 1
  • 10
  • 17
1

Consider enum as a special class type that can't be instantiated as regular class. Instead you have a special syntax to create one or more instances of enum inside enum declaration. But in almost all other aspects enums are just regular classes.

So, roughly speaking, you can consider following two code snippets identical:

    public enum Enum {
        INSTANCE1,
        INSTANCE2("name");

        private String name;

        private Enum () {
            name = "";
        }

        private Enum (String name) {
            this.name = name;
        }
    }


    public final class Class {
        public static final Class INSTANCE1 = new Class();
        public static final Class INSTANCE2 = new Class("name");

        private String name;

        private Class () {
            name = "";
        }

        private Class (String name) {
            this.name = name;
        }
    }

Of course there are plenty of differences, for example enums are final by default (you can't extend them), you can't create public constructor for enum, enums have special behavior during serializing/deserializing and so on. But after all, they are just regular classes, and you can expect them to behave like classes in common situations.

Aivean
  • 10,692
  • 25
  • 39