I create decorator pattern example:
interface:
public interface Printer {
void print(String message);
}
implementation:
public class StringPrinter implements Printer {
public void print(String message) {
System.out.println(message);
}
}
and 2 decorators:
change string to upper case:
public class UpCasePrinter implements Printer {
private Printer printer;
public UpCasePrinter(Printer printer) {
this.printer = printer;
}
public void print(String message) {
printer.print(message.toUpperCase());
}
}
print reverse string:
public class InversePrinter implements Printer {
private Printer printer;
public InversePrinter(Printer printer) {
this.printer = printer;
}
public void print(String message) {
StringBuilder builder = new StringBuilder(message);
printer.print(builder.reverse().toString());
}
}
All worck fine. But when I reading examples on different sites I faind another implementations. Each decarator extends
from another. And I saw the realization of BufferedInputStream
BufferedInputStream extends FilterInputStream
FilterInputStream extends InputStream
public abstract class InputStream implements Closeable
I can not understand the following:
-
Is there a difference in how to create a decorator? as for me - the decorator
implements
the same interface as the original class or as in the examples - the decorator isextends
from another decorator, etc. -
may be in the example with the BufferedInputStream such a realization only because the abstract class was chosen at the start and not the interface?
Aucun commentaire:
Enregistrer un commentaire