54 lines
2.0 KiB
Java
54 lines
2.0 KiB
Java
package decorator;
|
|
|
|
/**
|
|
* Decorator Design Pattern — Runnable Demo
|
|
*
|
|
* Shows how text processors can be stacked like Java IO streams.
|
|
* Each decorator adds one behaviour; the order of wrapping matters.
|
|
*
|
|
* Run: javac decorator/*.java && java decorator.Main
|
|
* Article: https://ankurm.com/decorator-design-pattern-java/
|
|
*/
|
|
public class Main {
|
|
|
|
public static void main(String[] args) {
|
|
System.out.println("=== Decorator Design Pattern Demo ===\n");
|
|
|
|
String input = " hello world, badword is here ";
|
|
System.out.println("Input: \"" + input + "\"");
|
|
System.out.println();
|
|
|
|
// Stack 1: just trim
|
|
TextProcessor trimOnly = new TrimDecorator(new PlainTextProcessor());
|
|
System.out.println("Trim only: \"" + trimOnly.process(input) + "\"");
|
|
|
|
// Stack 2: trim, then upper case
|
|
TextProcessor trimThenUpper =
|
|
new UpperCaseDecorator(
|
|
new TrimDecorator(
|
|
new PlainTextProcessor()));
|
|
System.out.println("Trim + UpperCase: \"" + trimThenUpper.process(input) + "\"");
|
|
|
|
// Stack 3: trim, filter profanity, then upper case
|
|
TextProcessor full =
|
|
new UpperCaseDecorator(
|
|
new ProfanityFilterDecorator(
|
|
new TrimDecorator(
|
|
new PlainTextProcessor())));
|
|
System.out.println("Trim + Filter + Upper: \"" + full.process(input) + "\"");
|
|
|
|
// Stack 4: different order — filter then trim (order matters!)
|
|
TextProcessor filterFirst =
|
|
new TrimDecorator(
|
|
new ProfanityFilterDecorator(
|
|
new PlainTextProcessor()));
|
|
System.out.println("Filter + Trim: \"" + filterFirst.process(input) + "\"");
|
|
|
|
System.out.println();
|
|
System.out.println("JDK parallel: new BufferedReader(new InputStreamReader(socket.getInputStream()))");
|
|
System.out.println("Same pattern: each wrapper adds one behaviour, order matters.");
|
|
|
|
System.out.println("\n=== Demo complete ===");
|
|
}
|
|
}
|