LearnFrenzy
Sign in Take a free test

Interfaces · Interfaces Programs · Question 7

Text-processing plugins through an interface in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

Define a TextPlugin interface (name, process) and a pipeline that runs enabled plugins in order; implement trim, collapse-spaces, title-case and profanity-mask plugins.

Solution
Main.java
import java.util.ArrayList;
import java.util.List;

interface TextPlugin {
    String name();
    String process(String text);
}

class Trim implements TextPlugin {
    public String name() { return "trim"; }
    public String process(String t) { return t.strip(); }
}

class CollapseSpaces implements TextPlugin {
    public String name() { return "collapse"; }
    public String process(String t) { return t.replaceAll("\\s+", " "); }
}

class TitleCase implements TextPlugin {
    public String name() { return "title"; }
    public String process(String t) {
        StringBuilder sb = new StringBuilder();
        for (String w : t.split(" ")) if (!w.isEmpty()) sb.append(Character.toUpperCase(w.charAt(0))).append(w.substring(1).toLowerCase()).append(' ');
        return sb.toString().trim();
    }
}

class Mask implements TextPlugin {
    private final List<String> banned;
    Mask(String... banned) { this.banned = List.of(banned); }
    public String name() { return "mask"; }
    public String process(String t) {
        for (String b : banned) t = t.replaceAll("(?i)\\b" + b + "\\b", "*".repeat(b.length()));
        return t;
    }
}

public class Main {
    public static void main(String[] args) {
        List<TextPlugin> pipeline = new ArrayList<>(List.of(new Trim(), new CollapseSpaces(), new Mask("silly"), new TitleCase()));
        String text = "   this   is a SILLY    example   ";
        for (TextPlugin p : pipeline) {
            text = p.process(text);
            System.out.println(String.format("%-9s", p.name()) + "[" + text + "]");
        }
    }
}

Output Verified by compiling and running

trim     [this   is a SILLY    example]
collapse [this is a SILLY example]
mask     [this is a ***** example]
title    [This Is A ***** Example]

The pipeline only knows the TextPlugin interface; plugins can be added, removed or reordered freely.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links