Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Decorator design pattern in Java
- // 2026-05-07
- // tested on Win with javac 21.0.2
- import java.util.*;
- // interface was added second to have an abstraction
- // an not to overload the Word class
- interface Gettable {
- public String get();
- }
- // this was the first class to add,
- // we wanted to have a word which we decided
- // to be able to modify late
- class Word implements Gettable {
- private String word;
- public Word(String word){
- this.word = word;
- }
- public String get(){
- return word;
- }
- }
- // third, now we can add the class to implement
- // the Decorator pattern, i.e. WordDecorator acts
- // like a Proxy and also satisfies the Gettable interface
- // (note both the composition and the inheritence).
- // We make this class abstract because it is designed
- // to be inherited by the derived classes (decorators) below
- abstract class WordDecorator implements Gettable {
- protected Gettable gettable;
- public WordDecorator(Gettable gettable){
- this.gettable = gettable;
- }
- abstract public String get();
- }
- // we add exclamation mark in the end regardless of the word
- class ExclDecorator extends WordDecorator {
- public ExclDecorator(Gettable gettable){
- super(gettable);
- }
- public String get(){
- return gettable.get() + "!";
- }
- }
- // we add quotes around the word regardless of the word
- class QuoteDecorator extends WordDecorator {
- public QuoteDecorator(Gettable gettable){
- super(gettable);
- }
- public String get(){
- return "\"" + gettable.get() + "\"";
- }
- }
- public class Main {
- // sample delegates to simplify the call to
- // System.out.print and System.out.println
- public static void print(String text){
- System.out.print(text);
- }
- public static void println(String text){
- System.out.println(text);
- }
- public static void main(String[] args){
- // and here is the testing scenario:
- // simple word first, nothing unusual
- Gettable w = new Word("Hello");
- println(w.get());
- // we decorate the word
- Gettable d1 = new ExclDecorator(w);
- println(d1.get());
- // we also decorate the word, but differently
- Gettable d2 = new QuoteDecorator(w);
- println(d2.get());
- // and now the power of the Decorator:
- // we can stack the decorators on top of each other
- // which allows to dynamically change the functionality.
- // Each Decorator adds their own thing and builds
- // on the layer below.
- Gettable d3 = new QuoteDecorator(d1);
- println(d3.get());
- }
- }
Advertisement