1
2
3
4
5 abstract class Display {
6 public abstract int getColumns();
7 public abstract int getRows();
8 public abstract String getRowText(int row);
9 public final void show() {
10 for(int i=0; i < getRows(); i++) {
11 System.out.println(getRowText(i));
12 }
13 }
14 }
15
16 class StringDisplay extends Display {
17 private String string;
18 public StringDisplay(String string) {
19 this.string = string;
20 }
21 public int getColumns() {
22 return string.getBytes().length;
23 }
24 public int getRows() {
25 return 1;
26 }
27 public String getRowText(int row) {
28 if(row == 0) {
29 return string;
30 } else {
31 return null;
32 }
33 }
34 }
35
36 abstract class Border extends Display {
37 protected Display display;
38 protected Border(Display display) {
39 this.display = display;
40 }
41 }
42
43 class SideBorder extends Border {
44 private char borderChar;
45 public SideBorder(Display display, char ch) {
46 super(display);
47 this.borderChar = ch;
48 }
49 public int getColumns() {
50 return 1 + display.getColumns() + 1;
51 }
52 public int getRows() {
53 return display.getRows();
54 }
55 public String getRowText(int row) {
56 return borderChar + display.getRowText(row) + borderChar;
57 }
58 }
59
60 class FullBorder extends Border {
61 public FullBorder(Display display) {
62 super(display);
63 }
64 public int getColumns() {
65 return 1 + display.getColumns() + 1;
66 }
67 public int getRows() {
68 return 1 + display.getRows() + 1;
69 }
70 public String getRowText(int row) {
71 if(row == 0) {
72 return "+" + makeLine('-', display.getColumns()) + "+";
73 } else if(row == display.getRows()+1) {
74 return "+" + makeLine('-', display.getColumns()) + "+";
75 } else {
76 return "|" + display.getRowText(row-1) + "|";
77 }
78 }
79 private String makeLine(char ch, int count) {
80 StringBuffer buf = new StringBuffer();
81 for(int i=0; i < count; i++) {
82 buf.append(ch);
83 }
84 return buf.toString();
85 }
86 }
87
88 public class DecoratorDisplay {
89 public static void main(String[] args) {
90 Display b1 = new StringDisplay("Hello, world.");
91 Display b2 = new SideBorder(b1, '#');
92 Display b3 = new FullBorder(b2);
93 b1.show();
94 b2.show();
95 b3.show();
96
97 Display b4 = new SideBorder(
98 new FullBorder(
99 new FullBorder(
100 new SideBorder(
101 new FullBorder(b1), '*'
102 )
103 )
104 ), '/'
105 );
106 b4.show();
107 }
108 }