Suppose I want to use the Decorator pattern to add functionality to the java.lang.String class. (Just for example, to add a toRussian() method.) String is a final class. Is the following the only way to do it?
class DecoratedString implements Serializable, CharSequence,
Comparable<DecoratedString>
{
private final String str;
public DecoratedString (String str) {
this.str = str;
}
public DecoratedString toRussian() {
...
}
public String toString() { return str; }
public int hashCode() { return str.hashCode(); }
public boolean equals(Object obj) { /* don't forget this one */ }
public char charAt(int index) { return str.charAt(index);}
public int codePointAt(int index) { return str.codePointAt(index);}
... and so on for 30 or so more methods of String ...
}
Usage:
String greeting = new DecoratedString("Hello, world!").toRussian().toString();
Postscript: This is so EASY to do in Objective-C with "Categories". Python now has @Decorators. And of course it's trivial in JavaScript, where you routinely add trim() to the String prototype. Is it totally impossible in Java?
Postpostscript: OK, toRussian() is a bad example. How would you add trim(), if String didn't already have trim()? trim() is an example of something every String should have.