Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

76
Vistas
Applying the Decorator Pattern to Java String Class

I want to add functionality to the java.lang.String class. I thought of using the decorator pattern as follows:

public class StringDecorator {

    String str;
    public StringDecorator(String str)
    {
        this.str = str;         
    }

    // Wrap all methods in String class such as:    
    public int length()
    {
        return str.length();
    }

    // Add other methods from String class here.. And then add new functions..

    public void newFunction1()
    {

    }
}

However, I read on SO here: https://stackoverflow.com/a/3945482 that this is not appropriate because String is final and cannot be extended. The user also suggests that "a different design pattern is probably in order".

Can someone please confirm if indeed it is not appropriate to use the decorator pattern in this scenario and if so what other design pattern can be used instead?

8 months ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

One problem with this is that in the decorator pattern, the decorator and the object being wrapped usually implement a common interface:

interface Interface {...}
class A implements Interface {...}
class ADecorator implements Interface {...}

So that where a method expects an Interface, both an A and ADecorator can be passed.

But in the case of String, almost all API using it require the implementation type String and not the interface type, CharSequence. So when you create this wrapper, you can not just use it with a method requiring a String. And since String is final you can't extend it and get around the problem that way.


What you have is still be useful, but it should be viewed as composition, and it would be helpful to have a getString (or whatever) method to retrieve the wrapped object (as someone suggested), so that you can still use it with methods requiring a String.

Assuming you will also make your class immutable, it could still be useful to have those delegating methods, but instead return an instance of the wrapper class:

public StringDecorator replace(char oldChar, char newChar) {
    return new StringDecorator(str.replace(oldChar, newChar));
}

But in most cases, you could get away with something like decorator.getString().length().

8 months ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos