These patterns are implemented using Java 8 Lambdas (together with Project Lombok annotations).
Enum class:
@RequiredArgsConstructor
@Getter
public static enum ShapeType {
CIRCLE( Circle::new),
RECTANGLE( Rectangle::new);
private final Supplier<Shape> constructor;
}
Factory method:
public static Shape createShape( ShapeType type) {
return type.getConstructor().get();
}
Enum class:
@RequiredArgsConstructor
@Getter
public static enum ShapeType {
CIRCLE( s, t -> new Circle( s, t)),
RECTANGLE( s, t -> new Rectangle( s, t));
private final ShapeConstructor constructor;
}
Functional Interface:
@FunctionalInterface
public interface ShapeConstructor {
Shape create( String s, int t);
}
Factory method:
public static Shape createShape( ShapeType type, String name, int line) {
return type.getConstructor().create( name, line);
}
Enum class:
@RequiredArgsConstructor
@Getter
public enum ShapeType {
CIRCLE( s, t -> new Circle( s, t)),
RECTANGLE( s, t -> new Rectangle( s, t));
private final ShapeConstructor constructor;
}
Functional Interface:
@FunctionalInterface
public interface ShapeFactory {
Shape create( String s, int t);
}
Factory method:
public static ShapeFactory createFactory( ShapeType type) {
return type.getConstructor();
}
Factory use (version 1 - static factory replacement):
ShapeFactory.createFactory( CIRCLE).create( Color.RED, 2)
Factory use (version 2 - factory instance replacement):
ShapeFactory factory = ShapeFactory.createFactory( RECTANGLE);
...
Shape newShape = shapeFactory.create( Color.YELLOW, 1);
Strategy Interface:
public interface TextFormatStrategy {
Predicate<String> getFilter();
UnaryOperator<String> getFormatter();
}
Enum class:
@RequiredArgsConstructor
@Getter
public static enum StrategyType implements TextFormatStrategy {
PLAIN_TEXT( t -> true,
t -> t),
ERROR_TEXT( t -> t.startsWith( "ERROR" ),
t -> t.toUpperCase()),
SHORT_TEXT( t -> t.length() < 20 ,
t -> t.toLowerCase());
private final Predicate<String> filter;
private final UnaryOperator<String> formatter;
}
Usage - passing all the data into the recipient method:
public static void publishText(String text, TextFormatStrategy formatStrategy) {
if ( formatStrategy.getFilter().test( text )) {
System.out.println( formatStrategy.getFormatter().apply( text ) );
}
}
...
List<String> messages = Arrays.asList( "DEBUG - I'm here", "ERROR - something bad happened");
messages.forEach( t -> publishText( t, TextFormatStrategy.StrategyType.PLAIN_TEXT));
Usage - passing just the strategy and returning a functional method to receive the parameters:
public static Consumer<String> publishText( TextFormatStrategy formatStrategy) {
return t -> {
if ( formatStrategy.getFilter().test( t )) {
System.out.println( formatStrategy.getFormatter().apply( t) );
}};
}
...
List<String> messages = Arrays.asList( "DEBUG - I'm here", "ERROR - something bad happened");
messages.forEach( publishText( TextFormatStrategy.StrategyType.PLAIN_TEXT)::accept);