This is the 7th day of my participation in the August Text Challenge.More challenges in August

1. The significance of enumeration

A lot of times we compare enumerations to constants, but in fact we use enumerations a lot in our programs to replace constants. Because enumerated classes are more intuitive and safer to type than static constants.

1.1 security

If a method requires direction, the parameter is of type int. The developer can pass in any type of int, but only the object contained in the enumerated class.

1.2 The namespace

Developers should start the names with SEASON_ so that another developer can look at the code and know that the four constants represent locations.

2, the application of enumeration

Enumeration is a new feature in JDK1.5 that is defined using the keyword enum. Enumerations have the following characteristics:

2.1 Features:
  • Enum has the same status as class and interface
  • Enum classes defined using enum inherit from java.lang. enum by default, not from Object, and enumerated classes can implement one or more interfaces.
  • All instances of the enumerated class must be displayed on the first line, without the use of the new keyword, and without the explicit call to the constructor. Automatically add public static final decoration.
  • Non-abstract enumerated classes defined with enum use final by default and cannot be inherited.
  • The constructor of an enumerated class can only be private.
2.2 Use:

We mentioned earlier that enumerations are usually used as arguments. Java5 added the enum keyword and extended the switch… A case expression in a case structure writes an enumeration value directly, and does not need to add an enumeration class as a qualification.

3, enumeration of special gameplay

So what’s special about enumerations other than replacing constants? Of course there are, like the following:

3.1 Singleton Mode

The singleton pattern is a design pattern that every Java developer must master. The implementation of the singleton pattern is usually referred to as the full and hungry, and there are also commonly referred to as the double judgment. Today we introduce another way to implement it with the help of enumeration:

public enum SingleEnum {
    INSTANCE;

    public void print(String word) { System.out.println(word); }}@Test
public void testSingle(a) {
    SingleEnum.INSTANCE.print("hello world");
}
Copy the code

As mentioned above, implementing the singleton pattern with enumerations is really simple, declaring the class as an enumeration and defining only one value internally. This is mainly based on the three features of enumerations: enumerations cannot be new, so singletons, enumerations cannot be inherited, and classes cannot be instantiated when they are not loaded.

Singletons created using enumerated classes also have the advantage of not being able to break their singletons with reflection, which is an advantage over other implementations. However, this is not common in real projects because we are used to using enumerations as constants and rarely add complex business logic to lift classes.

3.2 Policy Mode

In addition to easily implementing the singleton pattern above, enumerations can also implement policy patterns very simply, as in this example:

I have an interface that determines where the final data is going to be based on the parameters that I take, and if I write it normally, it might be a lot of if/else, right

public void save(String type, Object data) {
    if ("db".equals(type) {
        // Save to db
        saveInDb(data);
    } else if ("file".equals(type)) 
        // Save to a file
        saveInFile(data);
    } else if ("oss".eqauls(type)) {
        // Save in osssaveInOss(type); }}Copy the code

This is pretty straightforward, but when you add more types, this if/else line of code gets bigger and bigger, and it doesn’t look pretty. It would be much better to solve the if/else problem above with enumerations instead, based on the idea of a policy pattern.

public enum SaveStrategyEnum {
    DB("db") {
        @Override
        public void save(Object obj) {
            System.out.println("save in db:" + obj);
        }
    },
    FILE("file") {
        @Override
        public void save(Object obj) {
            System.out.println("save in file: " + obj);
        }
    },
    OSS("oss") {
        @Override
        public void save(Object obj) {
            System.out.println("save in oss: "+ obj); }};private String type;

    SaveStrategyEnum(String type) {
        this.type = type;
    }

    public abstract void save(Object obj);

    public static SaveStrategyEnum typeOf(String type) {
        for (SaveStrategyEnum strategyEnum: values()) {
            if (strategyEnum.type.equalsIgnoreCase(type)) {
                returnstrategyEnum; }}return null; }}public void save(String type, Object data) {
    SaveStrategyEnum strategyEnum = SaveStrategyEnum.typeOf(type);
    if(strategyEnum ! =null) { strategyEnum.save(data); }}Copy the code

The above main use is abstract class + enumeration to complete different strategy concrete implementation, this implementation method, compared with the previous singleton mode, or a little more common, although the overall look is not difficult, but a closer look, there will be two findings: The use of abstract methods (especially useful in template design patterns), using values() provided by enumerations natively, to traverse and find the target.

Above is my understanding of enumeration, there are many unexpected benefits in the actual use, the use is really very flexible and convenient! Welcome to leave a message to discuss ~