Implements Interface and Singleton pattern


Implements Interface

This is an enum that is also a callable function that tests String inputs against precompiled regular expression patterns.

import java.util.function.Predicate;
import java.util.regex.Pattern;
 
enum PatternMatcher implements Predicate<String> {
    ALPHABETIC("[A-Za-z]+"), EMAIL("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}");
 
    private final Pattern pattern;
 
    private PatternMatcher(final String pattern) {
        this.pattern = Pattern.compile(pattern);
    }
 
    @Override
    public boolean test(final String input) {
        return this.pattern.matcher(input).matches();
    }
}
 
public class Validator {
    public static void main(String[] args) {
        System.out.println(PatternMatcher.ALPHABETIC.test("SampleText"));
        System.out.println(PatternMatcher.EMAIL.test("example@example.com"));
    }
}

Each member of the enum can also implement the method:

import java.util.function.Predicate;
 
enum StringCheck implements Predicate<String> {
    MISSING {
        @Override
        public boolean test(String s) {
            return s == null;
        }
    },
    BLANK {
        @Override
        public boolean test(String s) {
            return s.equals("");
        }
    },
    MISSING_OR_BLANK {
        @Override
        public boolean test(String s) {
            return MISSING.test(s) || BLANK.test(s);
        }
    };
}
 
public class StringValidator {
    public static void main(String[] args) {
        System.out.println(StringCheck.MISSING.test(null)); // true
        System.out.println(StringCheck.BLANK.test("")); // true
        System.out.println(StringCheck.MISSING_OR_BLANK.test("Some Text")); // false
    }
}

Implement Singleton pattern with a single-element enum

Enum constants are instantiated when an enum is referenced for the first time. Therefore, that allows to implement Singleton software design pattern with a single-element enum.

public enum Attendant {
	INSTANCE;
	private Attendant() {
		// perform some initialization routine
	}
	public void sayHello() {
		System.out.println("Hello!");
	}
}
 
public class Main {
	public static void main(String... args) {
		Attendant.INSTANCE.sayHello();// instantiated at this point
	}
}

According to "Effective Java" book by Joshua Bloch, a single-element enum is the best way to implement a singleton. This approach has following advantages:

  • thread safety
  • guarantee of single instantiation
  • out-of-the-box serialization

And as shown in the section implements interface this singleton might also implement one or more interfaces.

Basic Programs