public interface IElement {
public void accept(IVisitor visitor);
}
public class ElementA implements IElement {
public void accept(IVisitor visitor) {
visitor.visit(this);
}
public void operationA() {
System.out.println(
"do A's job....such-and-such....");
}
}
public class ElementB implements IElement {
public void accept(IVisitor visitor) {
visitor.visit(this);
}
public void operationB() {
System.out.println(
"do B's job....such-and-such....");
}
}
public class ElementC implements IElement {
public void accept(IVisitor visitor) {
visitor.visit(this);
}
public void operationC() {
System.out.println(
"do C's job....such-and-such....");
}
}
public interface IVisitor {
public void visit(ElementA element);
public void visit(ElementB element);
public void visit(ElementC element);
}
public class VisitorA implements IVisitor {
public void visit(ElementA element) {
element.operationA();
}
public void visit(ElementB element) {
element.operationB();
}
public void visit(ElementC element) {
element.operationC();
}
}
public class Main {
public static void main(String[] args) {
// know nothing about their type
// after storing them into Element array
IElement[] list = {new ElementA(),
new ElementB(),
new ElementC()};
IVisitor visitor = new VisitorA();
for (int i=0; i < list.length; i++)
list[i].accept(visitor);
}
}
public class VisitorB implements IVisitor {
public void visit(ElementA element) {
System.out.println("VisitorB is a hard worker....");
element.operationA();
System.out.println(
"I want to do some extra work on A....");
}
public void visit(ElementB element) {
System.out.println("VisitorB is a hard worker....");
element.operationB();
System.out.println(
"I want to do some extra work on B....");
}
public void visit(ElementC element) {
System.out.println("VisitorB is a hard worker....");
element.operationC();
System.out.println(
"I want to do some extra work on C....");
}
}
public class Main {
public static void main(String[] args) {
IElement[] list = {new ElementA(),
new ElementB(),
new ElementC()};
System.out.println("visitorA is coming.......");
IVisitor visitorA = new VisitorA();
for (int i=0; i < list.length; i++)
list[i].accept(visitorA);
System.out.println("\nvisitorB is coming.......");
IVisitor visitorB = new VisitorB();
for (int i=0; i < list.length; i++)
list[i].accept(visitorB);
}
}
public abstract class TextStrategy {
protected String text;
public TextStrategy(String text) {
this.text = text;
}
public abstract String replace();
}
public class LinuxStrategy extends TextStrategy {
public LinuxStrategy(String text) {
super(text);
}
public String replace() {
preOperation();
System.out.println(
text = text.replaceAll("@r@n", "@n"));
postOperation();
return text;
}
private void preOperation() {
System.out.println("LinuxStrategy preOperation");
}
private void postOperation() {
System.out.println("LinuxStrategy postOperation");
}
}
public class WindowsStrategy extends TextStrategy {
public WindowsStrategy(String text) {
super(text);
}
public String replace() {
startOperation();
System.out.println(
text = text.replaceAll("@n", "@r@n"));
endOperation();
return text;
}
private void startOperation() {
System.out.println("WindowsStrategy startOperation");
}
private void endOperation() {
System.out.println("WindowsStrategy endOperation");
}
}
public class TextCharChange {
public static void replace(TextStrategy strategy) {
strategy.replace();
}
}
public class Main {
public static void main(String[] args) {
String linuxText =
"This is a test text!!@n Oh! Line Return!!@n";
String windowsText =
"This is a test text!!@r@n Oh! Line Return@r@n";
// load file, suppose it's Linux's text file
// take the WindowsStrategy
// I want to change it to Windows' text file
TextCharChange.replace(
new WindowsStrategy(linuxText));
// such-and-such operation.....
System.out.println();
// load file, suppose it's Windows' text file
// take the LinuxStrategy
// I want to change it to Linux's text file
TextCharChange.replace(
new LinuxStrategy(windowsText));
}
}
public abstract class AbstractClass {
public void templateMethod() {
// step by step template to solve something
// implementor should follow those step
opStep1();
opStep2();
opStep3();
}
public abstract void opStep1();
public abstract void opStep2();
public abstract void opStep3();
}
public class ConcreteClass extends AbstractClass {
public abstract void opStep1() {
// implement the real operation
}
public abstract void opStep2() {
// implement the real operation
}
public abstract void opStep3() {
// implement the real operation
}
}
public class Originator {
private String name;
private String phone;
public Originator(String name, String phone) {
this.name = name;
this.phone = phone;
}
// Some operations make state changed
public void someOperation() {
name = "noboby";
phone = "911-911";
}
// recover object's state
public void setMemento(Memento m) {
this.name = m.getName();
this.phone = m.getPhone();
}
public Memento createMemento() {
return new Memento(name, phone);
}
public void showInfo() {
System.out.println("Name: " + name +
"\nPhone: " + phone + "\n");
}
}
public class Memento {
private String name;
private String phone;
public Memento(String name, String phone) {
this.name = name;
this.phone = phone;
}
public String getName() {
return name;
}
public String getPhone() {
return phone;
}
public void setName(String name) {
this.name = name;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
public class Caretaker {\
private Memento memento;
public void setMemento(Memento memento) {
this.memento = memento;
}
public Memento getMemento() {
return memento;
}
}
public class Main {
public static void main(String[] args) {
Originator originator =
new Originator("Justin", "888-8888");
Caretaker caretaker = new Caretaker();
// save object's memento
caretaker.setMemento(originator.createMemento());
originator.showInfo();
// some operations make the object's state changed
originator.someOperation();
originator.showInfo();
// use memento to recover object's state
originator.setMemento(caretaker.getMemento());
originator.showInfo();
}
}
涓婚 | 璩囨枡鐗╀歡 | ||
瑙€瀵熻€?/strong> | 瀹㈡埗绔竴 | 瀹㈡埗绔簩 | 瀹㈡埗绔笁 |
public class State {
private int state;
public State() {
state = 0;
}
public void switchFire() {
if (state == 0) {
state = 1;
System.out.println( "small fire" );
} else if (state == 1) {
state = 2;
System.out.println( "medium fire" );
} else if (state == 2) {
state = 3;
System.out.println( "large fire" );
} else {
state = 0;
System.out.println( "turning off" );
}
}
}
public class Main {
public static void main(String[] args) {
State state = new State();
state.switchFire();
state.switchFire();
state.switchFire();
state.switchFire();
}
}
public interface IState {
public void switchFire(FireSwitch sw);
}
public class OffState implements IState {
public void switchFire(FireSwitch sw) {
sw.setState(new SmallState());
System.out.println( "small fire" );
}
}
public class SmallState implements IState {
public void switchFire(FireSwitch sw) {
sw.setState(new MediumState());
System.out.println( "medium fire" );
}
}
public class MediumState implements IState {
public void switchFire(FireSwitch sw) {
sw.setState(new LargeState());
System.out.println( "large fire" );
}
}
public class LargeState implements IState {
public void switchFire(FireSwitch sw) {
sw.setState(new OffState());
System.out.println( "off fire" );
}
}
public class FireSwitch {
private State current;
public FireSwitch() {
current = new OffState();
}
public void setState(State s) {
current = s;
}
public void switchFire() {
current.switchFire(this);
}
}
public class Main {
public static void main(String[] args) {
FireSwitch fireSwitch = new FireSwitch();
fireSwitch.switchFire();
fireSwitch.switchFire();
fireSwitch.switchFire();
fireSwitch.switchFire();
}
}
public interface IState {
public void switchClockWise(FireSwitch sw);
public void switchCountClock(FireSwitch sw);
}
public class OffState implements IState {
public void switchClockWise(FireSwitch sw) {
sw.setState(new SmallState());
System.out.println("small fire");
}
public void switchCountClock(FireSwitch sw) {
sw.setState(new LargeState());
System.out.println("large fire");
}
}
public class SmallState implements IState {
public void switchClockWise(FireSwitch sw) {
sw.setState(new MediumState());
System.out.println("medium fire");
}
public void switchCountClock(FireSwitch sw) {
sw.setState(new OffState());
System.out.println("off fire");
}
}
public class MediumState implements IState {
public void switchClockWise(FireSwitch sw) {
sw.setState(new LargeState());
System.out.println("large fire");
}
public void switchCountClock(FireSwitch sw) {
sw.setState(new SmallState());
System.out.println("small fire");
}
}
public class LargeState implements State {
public void switchClockWise(FireSwitch sw) {
sw.setState(new OffState());
System.out.println("off fire");
}
public void switchCountClock(FireSwitch sw) {
sw.setState(new MediumState());
System.out.println("medium fire");
}
}
public class FireSwitch {
private State current;
public FireSwitch() {
current = new OffState();
}
public void setState(State s) {
current = s;
}
public void switchClockWise() {
current.switchClockWise(this);
}
public void switchCountClock() {
current.switchCountClock(this);
}
}
public class Main {
public static void main(String[] args) {
FireSwitch fireSwitch = new FireSwitch();
fireSwitch.switchClockWise();
fireSwitch.switchClockWise();
fireSwitch.switchClockWise();
fireSwitch.switchClockWise();
System.out.println();
fireSwitch.switchCountClock();
fireSwitch.switchCountClock();
fireSwitch.switchCountClock();
fireSwitch.switchCountClock();
}
}
------------------------------ dog ------------------------------ dog |
public interface INode {
public void parse(Context context);
}
// <program> ::= PROGRAM <command list>
public class ProgramNode implements INode {
private INode commandListNode;
public void parse(Context context) {
context.skipToken("PROGRAM");
commandListNode = new CommandListNode();
commandListNode.parse(context);
}
public String toString() {
return "[PROGRAM " + commandListNode + "]";
}
}
import java.util.Vector;
// <command list> ::= <command>* END
public class CommandListNode implements INode {
private Vector list = new Vector();
public void parse(Context context) {
while (true) {
if (context.currentToken() == null) {
System.err.println("Missing 'END'");
break;
} else if (
context.currentToken().equals("END")) {
context.skipToken("END");
break;
} else {
INode commandNode = new CommandNode();
commandNode.parse(context);
list.add(commandNode);
}
}
}
public String toString() {
return "" + list;
}
}
// <command> ::= <repeat command> | <primitive command>
public class CommandNode implements INode {
private INode node;
public void parse(Context context) {
if (context.currentToken().equals("REPEAT")) {
node = new RepeatCommandNode();
node.parse(context);
} else {
node = new PrimitiveCommandNode();
node.parse(context);
}
}
public String toString() {
return node.toString();
}
}
public class RepeatCommandNode implements INode {
private int number;
private INode commandListNode;
public void parse(Context context) {
context.skipToken("REPEAT");
number = context.currentNumber();
context.nextToken();
commandListNode = new CommandListNode();
commandListNode.parse(context);
}
public String toString() {
return "[REPEAT " + number + " "
+ commandListNode + "]";
}
}
// <primitive command> ::= PRINT <string>
// | SPACE | BREAK | LINEBREAK
public class PrimitiveCommandNode implements INode {
private String name;
private String text;
public void parse(Context context) {
name = context.currentToken();
context.skipToken(name);
if (!name.equals("PRINT") && !name.equals("BREAK")
&& !name.equals("LINEBREAK")
&& !name.equals("SPACE")) {
System.err.println("Undefined Command");
}
if (name.equals("PRINT")) {
text = context.currentToken();
name += text;
context.nextToken();
}
}
public String toString() {
return name;
}
}
import java.util.*;
public class Context {
private StringTokenizer tokenizer;
private String currentToken;
public Context(String text) {
tokenizer = new StringTokenizer(text);
nextToken();
}
public String nextToken() {
if (tokenizer.hasMoreTokens()) {
currentToken = tokenizer.nextToken();
} else {
currentToken = null;
}
return currentToken;
}
public String currentToken() {
return currentToken;
}
public void skipToken(String token) {
if (!token.equals(currentToken)) {
System.err.println("Warning: " + token +
" is expected, but " +
currentToken + " is found.");
}
nextToken();
}
public int currentNumber() {
int number = 0;
try {
number = Integer.parseInt(currentToken);
} catch (NumberFormatException e) {
System.err.println("Warning: " + e);
}
return number;
}
}
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
BufferedReader reader = new
BufferedReader(new FileReader(args[0]));
String text;
while ((text = reader.readLine()) != null) {
System.out.println("text = \"" +
text + "\"");
INode node = new ProgramNode();
node.parse(new Context(text));
System.out.println("node = " + node);
}
}
catch (ArrayIndexOutOfBoundsException e) {
System.err.println(
"Usage: java Main yourprogram.txt");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
PROGRAM PRINT xxx END
PROGRAM REPEAT 4 PRINT xxx END END
PROGRAM REPEAT 4 PRINT xxx PRINT "yyy" END END
$ java Main program.txt text = "PROGRAM PRINT xxx END" node = [PROGRAM [PRINTxxx]] text = "PROGRAM REPEAT 4 PRINT xxx END END" node = [PROGRAM [[REPEAT 4 [PRINTxxx]]]] text = "PROGRAM REPEAT 4 PRINT xxx PRINT "yyy" END END" node = [PROGRAM [[REPEAT 4 [PRINTxxx, PRINT"yyy"]]]] |
public interface INode {
public void parse(Context context);
public void execute();
}
// <program> ::= PROGRAM <command list>
public class ProgramNode implements INode {
private INode commandListNode;
public void parse(Context context) {
context.skipToken("PROGRAM");
commandListNode = new CommandListNode();
commandListNode.parse(context);
}
public void execute() {
commandListNode.execute();
}
public String toString() {
return "[PROGRAM " + commandListNode + "]";
}
}
import java.util.*;
// <command list> ::= <command>* END
public class CommandListNode implements INode {
private Vector list = new Vector();
private INode commandNode;
public void parse(Context context) {
while (true) {
if (context.currentToken() == null) {
System.err.println("Missing 'END'");
break;
} else if(context.currentToken().equals("END")) {
context.skipToken("END");
break;
} else {
commandNode = new CommandNode();
commandNode.parse(context);
list.add(commandNode);
}
}
}
public void execute() {
Iterator it = list.iterator();
while (it.hasNext()) {
((CommandNode)it.next()).execute();
}
}
public String toString() {
return "" + list;
}
}
// <command> ::= <repeat command> | <primitive command>
public class CommandNode implements INode {
private INode node;
public void parse(Context context) {
if (context.currentToken().equals("REPEAT")) {
node = new RepeatCommandNode();
node.parse(context);
} else {
node = new PrimitiveCommandNode();
node.parse(context);
}
}
public void execute() {
node.execute();
}
public String toString() {
return node.toString();
}
}
// <primitive command> ::= PRINT <string>
// | SPACE | BREAK | LINEBREAK
public class PrimitiveCommandNode implements INode {
private String name;
private String text;
public void parse(Context context) {
name = context.currentToken();
context.skipToken(name);
if (!name.equals("PRINT") && !name.equals("BREAK")
&& !name.equals("LINEBREAK")
&& !name.equals("SPACE")) {
System.err.println("Undefined Command");
}
if (name.equals("PRINT")) {
text = context.currentToken();
context.nextToken();
}
}
public void execute() {
if(name.equals("PRINT"))
System.out.print(text);
else if(name.equals("SPACE"))
System.out.print(" ");
else if(name.equals("BREAK"))
System.out.println();
else if(name.equals("LINEBREAK"))
System.out.println(
"\n------------------------------");
}
public String toString() {
return name;
}
}
public class RepeatCommandNode implements INode {
private int number;
private INode commandListNode;
public void parse(Context context) {
context.skipToken("REPEAT");
number = context.currentNumber();
context.nextToken();
commandListNode = new CommandListNode();
commandListNode.parse(context);
}
public void execute() {
for(int i = 0; i < number; i++)
commandListNode.execute();
}
public String toString() {
return "[REPEAT " + number + " " +
commandListNode + "]";
}
}
import java.util.*;
public class Context {
private StringTokenizer tokenizer;
private String currentToken;
public Context(String text) {
tokenizer = new StringTokenizer(text);
nextToken();
}
public String nextToken() {
if (tokenizer.hasMoreTokens()) {
currentToken = tokenizer.nextToken();
} else {
currentToken = null;
}
return currentToken;
}
public String currentToken() {
return currentToken;
}
public void skipToken(String token) {
if (!token.equals(currentToken)) {
System.err.println("Warning: " + token +
" is expected, but " +
currentToken + " is found.");
}
nextToken();
}
public int currentNumber() {
int number = 0;
try {
number = Integer.parseInt(currentToken);
} catch (NumberFormatException e) {
System.err.println("Warning: " + e);
}
return number;
}
}
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(
new FileReader(args[0]));
String text;
while ((text = reader.readLine()) != null) {
System.out.println("text = \"" + text
+ "\"");
INode node = new ProgramNode();
node.parse(new Context(text));
node.execute();
}
}
catch (ArrayIndexOutOfBoundsException e) {
System.err.println(
"Useage: java Main yourprogram.txt");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
PROGRAM REPEAT 4 LINEBREAK PRINT justin SPACE PRINT momor LINEBREAK END END
$ java Main program.txt text = "PROGRAM REPEAT 4 LINEBREAK PRINT justin SPACE PRINT momor LINEBREAK END END" ------------------------------ justin momor ------------------------------ ------------------------------ justin momor ------------------------------ ------------------------------ justin momor ------------------------------ ------------------------------ justin momor ------------------------------ |
import java.util.*;
public class Main {
public static void main(String[] args) {
List arrayList = new ArrayList();
for(int i = 0; i < 10; i++)
arrayList.add("Test " + i);
for(int i = 0; i < 10; i++)
System.out.println(arrayList.get(i).toString());
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
List arrayList = new ArrayList();
for(int i = 0; i < 10; i++)
arrayList.add("Test " +i);
visit(arrayList.iterator());
}
public static visit(Iterator iterator) {
while(iterator.hasNext())
System.out.println(iterator.next().toString());
}
}
import java.util.*;
class Hamster {
private int hamsterNumber;
Hamster(int i) { hamsterNumber = i; }
public String toString() {
return "This is Hamster #" + hamsterNumber;
}
}
class Printer {
static void printAll(Iterator e) {
while(e.hasNext()) {
System.out.println(e.next());
}
}
}
public class HamsterMaze {
public static void main(String[] args) {
ArrayList v = new ArrayList();
for(int i = 0; i < 3; i++) {
v.add(new Hamster(i));
}
Printer.printAll(v.iterator());
}
}
import java.util.*;
public class Invoker {
private Map commands;
public Invoker() {
commands = new HashMap();
}
public void addCommand(String commName,
ICommand command) {
commands.put(commName, command);
}
public void request(String commName) {
ICommand command = (ICommand) commands.get(commName);
command.execute();
}
}
public interface ICommand {
public void execute();
}
public class UpperCaseHello implements ICommand {
private String name;
public UpperCaseHello(String name) {
this.name = name;
}
public void execute() {
System.out.println("HELLO, " + name.toUpperCase());
}
}
public class LowerCaseHello implements ICommand {
private String name;
public LowerCaseHello(String name) {
this.name = name;
}
public void execute() {
System.out.println("hello, " + name.toLowerCase());
}
}
public class Client {
public static void main(String[] args) {
Invoker invoker = new Invoker();
invoker.addCommand("JUSTIN",
new UpperCaseHello("Justin"));
invoker.addCommand("momor",
new LowerCaseHello("momor"));
// simulate random request
String[] req = {"JUSTIN", "momor"};
while(true) {
int i = (int) (Math.random() * 10) % 2;
invoker.request(req[i]);
}
}
}
鍍忎笂闈㈤€欑ó灝囪珛姹傚皝瑁濊搗渚嗙殑妯″紡錛屽氨鏄疌ommand妯″紡錛屽畠灝囪珛姹傚緦鐨勫浣滈儴浠界暀寰呬嬌鐢ㄨ€呭浣滐紝Command妯″紡鐨刄ML欏炲垾鍦栧涓嬫墍紺猴細
public interface IHandler {
public void handle();
}
public class SymbolHandler implements IHandler {
public void handle() {
System.out.println("Symbol has been handled");
}
}
public class CharacterHandler implements IHandler {
public void handle() {
System.out.println("Character has been handled");
}
}
public class NumberHandler implements IHandler {
public void handle() {
System.out.println("Number has been handled");
}
}
import java.io.*;
public class Application {
public void run() throws Exception {
System.out.print("Press any key then return: ");
char c = (char) System.in.read();
IHandler handler = null;
if (Character.isLetter(c)) {
handler = new CharacterHandler();
}
else if (Character.isDigit(c)) {
handler = new NumberHandler();
}
else {
handler = new SymbolHandler();
}
handler.handle();
}
public static void main(String[] args)
throws IOException {
Application app = new Application();
app.run();
}
}
public class Handler {
private Handler successor;
public void setSuccessor(Handler successor) {
this.successor = successor;
}
public Handler getSuccessor() {
return successor;
}
public void handleRequest(char c) {
if(successor != null)
successor.handleRequest(c);
}
}
public class NumberHandler extends Handler {
public void handleRequest(char c) {
if(Character.isDigit(c)) {
System.out.println("Number has been handled");
}
else {
getSuccessor().handleRequest(c);
}
}
}
public class CharacterHandler extends Handler {
public void handleRequest(char c) {
if(Character.isLetter(c)) {
System.out.println("Character has been handled");
}
else {
getSuccessor().handleRequest(c);
}
}
}
public class SymbolHandler extends Handler {
public void handleRequest(char c) {
System.out.println("Symbol has been handled");
}
}
import java.io.*;
public class Application {
public static void main(String[] args)
throws IOException {
Handler numberHandler = new NumberHandler();
Handler characterHandler = new CharacterHandler();
Handler symbolHandler = new SymbolHandler();
numberHandler.setSuccessor(characterHandler);
characterHandler.setSuccessor(symbolHandler);
System.out.print("Press any key then return: ");
char c = (char)System.in.read();
numberHandler.handleRequest(c);
}
}
public class Request{
銆€銆€private String type;
public Request(String type) { this.type=type; }
銆€銆€public String getType() { return type; }
銆€銆€public void execute(){
// 鍩瘋璜嬫眰
銆€銆€}
}