package 设计模式.装饰器模式.例子1;
public interface TextConsole {
public void printWords();
public void readWords();
}
package 设计模式.装饰器模式.例子1;
public class DecoratorTextConsole implements TextConsole {
private TextConsole text;
public DecoratorTextConsole(TextConsole text) {
this.text = text;
}
@Override
public void printWords() {
text.printWords();
}
@Override
public void readWords() {
text.readWords();
}
}
package 设计模式.装饰器模式.例子1;
public class AsteriskTextConsole extends DecoratorTextConsole {
public AsteriskTextConsole(TextConsole text) {
super(text);
// TODO Auto-generated constructor stub
}
public void printWords() {
addAsterrisk();
super.printWords();
addAsterrisk();
}
private void addAsterrisk() {
System.out.print("*");
}
}
package 设计模式.装饰器模式.例子1;
public class DecoratorTextConsole implements TextConsole {
private TextConsole text;
public DecoratorTextConsole(TextConsole text) {
this.text = text;
}
@Override
public void printWords() {
text.printWords();
}
@Override
public void readWords() {
text.readWords();
}
}
package 设计模式.装饰器模式.例子1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MyText implements TextConsole {
private String words;
@Override
public void printWords() {
System.out.print(words);
}
@Override
public void readWords() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("Please enter some words to display");
br.readLine();
} catch (IOException e) {
e.printStackTrace();
words = "There are somew errors occurs during entering";
}
}
}
package 设计模式.装饰器模式.例子1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) {
TextConsole mt = new MyText();// mt 实例在整个被调用的过程中都不会改变.
// 但是它的其他装饰器类却是动态生成的,而且是可自由“拆卸”的,这样就比单一的继承灵活的多。
mt.readWords();
mt.printWords();
System.out.println();
String command = new String();
System.out
.println("please enter commond: (add ?(-plus | -astr | -all) | exit");
while (!command.equalsIgnoreCase("exit")) {
try {
command = new BufferedReader(new InputStreamReader(System.in))
.readLine();
} catch (IOException e) {
e.printStackTrace();
command = "exit";
}
if (command.equals("add -plus")) {
TextConsole ptc = new PlusTextConsole(mt);
ptc.printWords();
System.out.println();
} else if (command.equals("add -aster")) {
TextConsole atc = new AsteriskTextConsole(mt);
atc.printWords();
System.out.println();
} else if (command.equals("add -all")) {
TextConsole tc = new PlusTextConsole(
new AsteriskTextConsole(mt));
tc.printWords();
System.out.println();
}
}
}
}