Add all 23 GoF design pattern implementations (2026-06-13)
This commit is contained in:
53
02-structural/decorator/Main.java
Normal file
53
02-structural/decorator/Main.java
Normal file
@@ -0,0 +1,53 @@
|
||||
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 ===");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user