A simple sample callback pattern in java
String ・ CamelCase → snake_case ・ Lowercase → Uppercase Let's take the process of displaying after
NoCallbackPattern.java
public class NoCallbackPattern {
/**
*Snake from CamelCase_Convert to case
*/
private String camelToSnake(String input) {
return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, input);
}
/**
*Convert from lowercase to uppercase
*/
private String capitalize(String input) {
return input.toUpperCase();
}
/**
*Convert and display
*/
public void print(String input) {
System.out.println(capitalize(camelToSnake(input)));
}
}
Main.java
public class Main {
public static void main(String[] args) {
NoCallbackPattern noCallbackPattern = new NoCallbackPattern();
noCallbackPattern.print("replaceString");
}
}
CallbackPattern.java
public class CallbackPattern {
private List<MyFilter> myFilters;
public CallbackPattern(List<MyFilter> myFilters) {
this.myFilters = myFilters;
}
public void print(String input) {
String output = input;
for (MyFilter myFilter : myFilters) {
output = myFilter.replace(output);
}
System.out.println(output);
}
}
MyFilter.java
public interface MyFilter {
String replace(String input);
}
CamelToSnake.java
public class CamelToSnake implements MyFilter {
@Override
public String replace(String input) {
return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, input);
}
}
Capitalize.java
public class Capitalize implements MyFilter {
@Override
public String replace(String input) {
return input.toUpperCase();
}
}
Main.java
public class Main {
public static void main(String[] args) {
List<MyFilter> filters = Arrays.asList(new CamelToSnake(), new Capitalize());
CallbackPattern callbackPattern = new CallbackPattern(filters);
callbackPattern.print("replaceString");
}
}
** If you write using the callback pattern, you can see that the CallbackPattern class does not need to be modified when adding conversion processing because the print method depends only on the MyFilter interface **
Recommended Posts